[Chartjs]-Chart.js annotation horizontal line on double y-axis graph

2👍

You’ve changed the ID of the y-axes to A and B:

yAxes: [{
    id: 'A',
    ...
}, {
    id: 'B',
    ...

In the annotation plugin configuration you tell it to draw on y-axis-0 (which is the default ID):

annotation: {
    annotations: [{
        scaleID: 'y-axis-0',
        ...

Change the configuration to whichever y-axis you want to draw the annotation to:

scaleID: 'A'

Edit: Working example with Chart.js 2.7.2

var canvas = document.getElementById('chart').getContext("2d");
    new Chart(canvas, {
      type: 'line',
      data: {
        labels: ['Morning 6am-12pm', 'Afternoon 12pm-4pm', 'Evening 4pm-7pm', 'Night 7pm-12am', 'Dawn 12am-6am'],
        datasets: [{
          label: 'Temperature',
          yAxisID: 'A',
          data: [30, 32, 33, 31, 30]
        }, {
          label: 'Humidity',
          yAxisID: 'B',
          data: [80, 77, 74, 79, 83],
            lineTension: 0.3,
            fill: false,
            borderColor: 'lightblue',
            backgroundColor: 'transparent',
            pointBorderColor: 'lightblue',
            pointBackgroundColor: 'lightgreen',
            pointRadius: 5,
            pointHoverRadius: 15,
            pointHitRadius: 30,
            pointBorderWidth: 2
        }]
      },
      options: {
        scales: {
          yAxes: [{
            id: 'A',
            type: 'linear',
            position: 'left',
          }, {
            id: 'B',
            type: 'linear',
            position: 'right',
            ticks: {
              max: 100,
              min: 0
            }
          }]
        }, 
          annotation: {
            annotations: [{
            type: 'line',
            mode: 'horizontal',
            scaleID: 'A',
            value: 32,
            borderColor: 'rgb(75, 0, 0)',
            borderWidth: 4,
            label: {
              enabled: false,
              content: 'Test label'
            }
          }]
        }
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="chart"></canvas>

Leave a comment