Chartjs-Chartjs 2.9.4 Trying to make a fixed horizontal line

0👍

There are a couple of mistakes.

  1. Config: plugins node is set in the options one in your code. Instead, it should be defined in the same level of options, data and type (see below).
  2. Plugin: you are referring to the scales assuming that their IDs are x and y. In chartjs 2.x, the scales ids are not x and y (by default) but x/y-axis-0.
  3. Plugin: chart area in chartjs version 2 doesn’t have widht and height (they will come with version 3) therefore you should use right value to get the width.

EDIT: you could use also chartjs-plugin-annotation I guess.

    // setup 
    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };


 const horizontalLine = {
   id: 'horizontalLine',
   afterDatasetDraw(chart, args, options){
      const {ctx, chartArea: {top, right, bottom, left},
      scales:{y} } = chart;
      ctx.save();
      ctx.strokeStyle = 'green';
      ctx.strokeRect(left, y.getPixelForValue(12), right - left, 0);
      ctx.restore();
   }
 }



    // config 
    const config = {
      type: 'line',
      data,
      plugins: [horizontalLine],
      options: {
        scales: {
          yAxes: [{
                id: 'y',
                ticks: {
                    beginAtZero: true
                }
            }]
        },
        
      },
    };

    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment