Chartjs-Vertical lines for custom events and notes

1👍

You can draw you own lines directly on to the canvas using the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw dashed lines for points from the dataset that represent an event each.

The message bubbles can be drawn on the canvas using CanvasRenderingContext2D.drawImage().

const labels = ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'];
const events = ['2020-02-08', '2020-02-10'];
const values = [75, 56, 33, 44, 71, 62, 24];

var icon = new Image(20, 20);
icon.src = 'https://i.stack.imgur.com/EXAgg.png';

new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {      
      var ctx = chart.chart.ctx; 
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {         
         if (events.includes(labels[index])) {
           var x = xAxis.getPixelForTick(index);           
           ctx.save();
           ctx.setLineDash([10, 5]);
           ctx.strokeStyle = '#888888';
           ctx.beginPath();
           ctx.moveTo(x, yAxis.bottom);             
           ctx.lineTo(x, yAxis.top);
           ctx.stroke();
           ctx.restore();
           ctx.drawImage(icon, x - 12, yAxis.bottom - 15);
         }
      });      
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{        
        ticks: {
          beginAtZero: true,
          stepSize: 20
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        },
        gridLines: {
          display: false
        }        
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment