繁体   English   中英

Chart.js 仅绘制 y 轴到点

[英]Chart.js draw y-axis only up to point

我想知道如何仅将 y 轴绘制到一个数据集的点。 就像在这个例子中:

在此处输入图片说明

到目前为止,我已经通过在数据集上添加反向白色背景来尝试一个 hacky 版本,但是因为我在 x 轴上有一些偏移,白色背景突然切割,并且 Y 轴线变得隐藏。

有谁知道如何遍历每条网格线并给它正确的长度?

您可以使用插件核心 API将自己的线条直接绘制到canvas 它提供了可用于执行自定义代码的不同钩子。 在下面的代码片段中,我使用afterDraw钩子为数据集中的各个点绘制虚线。

 const data = [1, 3, 2]; 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.getPixelForValue(undefined, index); var yTop = yAxis.getPixelForValue(data[index]); ctx.save(); ctx.setLineDash([10, 5]); ctx.strokeStyle = '#888888'; ctx.beginPath(); ctx.moveTo(x, yAxis.bottom); ctx.lineTo(x, yTop); ctx.stroke(); ctx.restore(); }); } }], data: { labels: ["A", "B", "C"], datasets: [{ label: "My First Dataset", data: [1, 3, 2], fill: false, borderColor: "rgb(75, 192, 192)", lineTension: 0.3 }] }, options: { legend: { display: false }, scales: { xAxes: [{ offset: true, gridLines: { color: 'white' } }], yAxes: [{ ticks: { beginAtZero: true, max: 4, stepSize: 1 } }] } } });
 canvas { max-width: 200px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="myChart" width="10" height="10"></canvas>

暂无
暂无

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

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