Chart.js 只绘制 y 轴到点
Chart.js draw y-axis only up to point
我想知道如何只绘制 y 轴到一个数据集的点。就像这个例子:
到目前为止,我已经通过在数据集上添加一个反转的白色背景来尝试一个 hacky 版本,但是因为我在 x 轴上有一些偏移量,所以白色背景突然被切断,并且 Y 轴线被隐藏。
有谁知道如何遍历每条网格线并给它正确的长度?
您可以使用 Plugin Core 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>
我想知道如何只绘制 y 轴到一个数据集的点。就像这个例子:
到目前为止,我已经通过在数据集上添加一个反转的白色背景来尝试一个 hacky 版本,但是因为我在 x 轴上有一些偏移量,所以白色背景突然被切断,并且 Y 轴线被隐藏。
有谁知道如何遍历每条网格线并给它正确的长度?
您可以使用 Plugin Core 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>