简体   繁体   English

如何为 Chart.js 中的每个点添加垂直线和 label?

[英]How can I add vertical line and label for each point in Chart.js?

How can I add a vertical line for each point and make the selected data to appear with a 5.5k label like on the below screenshot?如何为每个点添加一条垂直线并使所选数据显示为 5.5k label,如下面的屏幕截图所示?

带有垂直线的图表

You can draw your own lines directly on to the canvas using the Plugin Core API .您可以使用插件核心 API直接在canvas上绘制自己的线条。 It offers different hooks that may be used for executing custom code.它提供了不同的钩子,可用于执行自定义代码。 In below code snippet, I use the afterDraw hook to draw vertical lines up to the individual points from the dataset.在下面的代码片段中,我使用afterDraw钩子将垂直线绘制到数据集中的各个点。

 const data = [65, 0, 80, 81, 56, 85, 40]; new Chart(document.getElementById("myChart"), { type: 'line', plugins: [{ afterDraw: chart => { var ctx = chart.chart.ctx; var xAxis = chart.scales['x-axis-0']; var yAxis = chart.scales['y-axis-0']; xAxis.ticks.forEach((value, index) => { var x = xAxis.getPixelForTick(index); var yTop = yAxis.getPixelForValue(data[index]); ctx.save(); ctx.strokeStyle = '#aaaaaa'; ctx.beginPath(); ctx.moveTo(x, yAxis.bottom); ctx.lineTo(x, yTop); ctx.stroke(); ctx.restore(); }); } }], data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", data: data, fill: false }] }, options: { legend: { display: false }, scales: { yAxes: [{ gridLines: { display: false } }], xAxes: [{ gridLines: { display: false } }] } } });
 <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js'></script> <div style="width: 75%"> <canvas id="myChart" height="90"></canvas> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM