I have been struggeling to get this working. I do not want to use any plugins, I just want to draw a simple horizontal line which starts at a specific value on the y-axis.
Can anyone please tell me if this is possible and if, how to do it in chartjs 3.7.1?
I know how to draw shapes, but I am unable to figure out how to get the pixels (starting point) of a specific value from the y-axis.
const indicatorA = {
id: 'indicatorA ',
afterDraw(chart, args, options) {
console.log(chart)
}
}
Basically what I want to do is write a simple plugin that will draw the line when the chart is loaded.
>Solution :
This can be done with the Plugin Core API, in the afterDraw hook as follows:
afterDraw: chart => {
const ctx = chart.ctx;
ctx.save();
const xAxis = chart.scales['x'];
const yAxis = chart.scales['y'];
const y = yAxis.getPixelForValue(yValueVerticalLine);
ctx.beginPath();
ctx.moveTo(xAxis.left, y);
ctx.lineTo(xAxis.right, y);
ctx.lineWidth = 2;
ctx.strokeStyle = 'green';
ctx.stroke();
ctx.restore();
}
Please take a look at below runnable code and see how it works.
const yValueVerticalLine = 8;
var chart = new Chart('canvas', {
type: 'line',
plugins: [{
afterDraw: chart => {
const ctx = chart.ctx;
ctx.save();
const xAxis = chart.scales['x'];
const yAxis = chart.scales['y'];
const y = yAxis.getPixelForValue(yValueVerticalLine);
ctx.beginPath();
ctx.moveTo(xAxis.left, y);
ctx.lineTo(xAxis.right, y);
ctx.lineWidth = 2;
ctx.strokeStyle = 'green';
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F'],
datasets: [{
label: 'Dataset 1',
data: [13, 10, 12, 13, 9, 12],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
fill: false
},
{
label: 'Dataset 2',
data: [10, 7, 9, 10, 6, 9],
backgroundColor: 'rgba(255, 159, 64, 0.2)',
borderColor: 'rgb(255, 159, 64)'
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>