您可以使用Plugin Core API在画布上直接绘制网格线标签。它提供了许多可用于执行自定义代码的挂钩。根据您的情况,可以使用afterDraw
钩子并通过CanvasRenderingContext2D
画线,如下面的可运行代码片段所示。
CanvasRenderingContext2D
new Chart(document.getElementById("chart"), {
type: "bar",
plugins: [{
afterDraw : chart => {
var ctx = chart.chart.ctx;
ctx.save();
ctx.globalCompositeOperation = "destination-over";
var xAxis = chart.scales["x-axis-0"];
var yAxis = chart.scales["y-axis-0"];
yAxis.ticks.forEach((v, i) => {
var y = yAxis.getPixelForTick(i);
ctx.strokeStyle = 'rgb(128, 128, 128, 0.3)';
ctx.lineWidth = 1;
ctx.setLineDash(v < 0 ? [10, 5] : []);
ctx.beginPath();
ctx.moveTo(xAxis.left, y);
ctx.lineTo(xAxis.right, y);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
labels: ["A", "B", "C"],
datasets: [{
label: "Dataset 1",
data: [10, 15, 10],
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)"],
borderWidth: 1
},
{
label: "Dataset 2",
data: [-15, -10, -15],
backgroundColor: "rgba(0, 255, 0, 0.2)",
borderColor: "rgb(0, 255, 0)",
borderWidth: 1
}
]
},
options: {
layout: {
padding: {
left: 12
}
},
legend: {
display: false
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
}
}],
yAxes: [{
stacked: true,
gridLines: {
drawOnChartArea: false
},
ticks: {
stepSize: 5
}
}]
}
}
});
canvas {
max-width: 400px;
}