Chartjs-Chartjs 3 how to draw a horizontal line starting at a specific yAxis value

0👍

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>

Leave a comment