[Chartjs]-Is it possible to draw a bar and arrow/pointer on the right side of a chart?

1👍

You can write a custom plugin for this, I added padding on the right to give space for the arrow to be drawn. You can play with the multiplyer values to make the arrow bigger/smaller

Example:

var randoms = [...Array(11)].map(e => ~~(Math.random() * 11));
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: randoms,
    datasets: [{
      label: 'value',
      data: randoms,
      borderColor: 'red',
      backgroundColor: 'red'
    }]
  },
  options: {
    layout: {
      padding: {
        right: 25
      }
    },
    scales: {
      y: {
        grace: 10
      }
    }
  },
  plugins: [{
    id: 'arrow',
    afterDraw: (chart, args, opts) => {
      const {
        ctx
      } = chart;
      chart._metasets.forEach((meta) => {
        let point = meta.data[meta.data.length - 1];
        ctx.save();
        ctx.fillStyle = point.options.backgroundColor;
        ctx.moveTo(point.x, (point.y - point.y * 0.035));
        ctx.lineTo(point.x, (point.y + point.y * 0.035));
        ctx.lineTo((point.x + point.x * 0.025), point.y)
        ctx.fill();
        ctx.restore();
      })
    }
  }]
});

function populate() {
  let temp = ~~(Math.random() * 11);
  myChart.data.datasets[0].data.shift();
  myChart.data.datasets[0].data.push(temp);

  myChart.update();
}

//setInterval(populate, 10000);
<script src="https://npmcdn.com/chart.js@latest/dist/chart.min.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment