2👍
✅
You can draw your own line directly on to the canvas using the Plugin Core API together with CanvasRenderingContext2D
. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw
hook to draw a dashed horizontal line from the last data point up to the the position of the next tick.
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'];
var dataset = chart.config.data.datasets[0];
var data = dataset.data;
var xFrom = xAxis.getPixelForTick(data.length - 1);
var xTo = xAxis.getPixelForTick(data.length);
var y = yAxis.getPixelForValue(data[data.length - 1]);
ctx.save();
ctx.strokeStyle = dataset.borderColor;
ctx.lineWidth = dataset.lineWidth;
ctx.setLineDash([8, 4]);
ctx.beginPath();
ctx.moveTo(xFrom, y);
ctx.lineTo(xTo, y);
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ["1", "2", "3", "4", "5", "6"],
datasets: [{
label: "My Dataset",
data: [5, 1, 3],
borderColor: 'red',
lineWidth: 3,
steppedLine: 'before',
fill: false
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}],
}
}
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js'></script>
<canvas id="myChart" height="90"></canvas>
Source:stackexchange.com