[Chartjs]-How to put indicator between yAxis values on yAxis chartJs?

1πŸ‘

βœ…

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw an image directly on the canvas using CanvasRenderingContext2D as follows.

plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    var xAxis = chart.scales['x-axis-0'];
    var yAxis = chart.scales['y-axis-0'];
    var image = new Image();
    image.src = 'https://i.stack.imgur.com/zyhEv.png',
    ctx.drawImage(image, xAxis.left - 11, yAxis.bottom - 16, 20, 10);    
    ctx.restore();
  }
}],

Please take a look at the following runnable code and see how it works.

new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      var image = new Image();
      image.src = 'https://i.stack.imgur.com/zyhEv.png',
      ctx.drawImage(image, xAxis.left - 10, yAxis.bottom - 16, 20, 10);     
      ctx.restore();
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "APAC RE index",
      data: [0.7, 0.8, 0.9, 1, 0.9, 0.8, 0.7],
      fill: false,
      borderColor: "rgb(255, 0, 0)"
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0.65,
          stepSize: 0.1,
          callback: (value, index, values) => index + 1 == values.length ? 0 : value
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

~

0πŸ‘

try using box annotation and assign the y-axis and x-axis range to it.

annotation: {
      annotations: [{
        drawTime: 'afterDraw', // overrides annotation.drawTime if set
        id: 'a-line-1', // optional
        type: 'box',
        borderWidth: 10,
        borderColor: 'green',
        xScaleID: 'x-axis-0',
        yScaleID: 'y-axis-0',
        xMin: "January",
        xMax: "January",
        yMax: 0.7,
        yMin: 0.0,
      }]
    }

here is the fiddle

Leave a comment