Chartjs-How to add multi X axis custom line in chart js

0👍

This is a work around:

var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    originalLineDraw.apply(this, arguments);

    var chart = this.chart;
    var ctx = chart.chart.ctx;

    var index = chart.config.data.lineAtIndex;
    if (index) {
      var xaxis = chart.scales['x-axis-0'];
      var yaxis = chart.scales['y-axis-0'];

      var aaxis = chart.scales['x-axis-0'];
      var yyaxis = chart.scales['y-axis-0'];

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(xaxis.getPixelForValue(undefined, index), yaxis.top);
      ctx.strokeStyle = '#ff0000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);

      ctx.moveTo(aaxis.getPixelForValue(undefined, index + 1), yyaxis.top);
      ctx.strokeStyle = '#cc0000';
      ctx.lineTo(aaxis.getPixelForValue(undefined, index + 1), yyaxis.bottom);

      ctx.stroke();
      ctx.restore();
    }
  }
});

var config = {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      data: [65, 0, 80, 81, 56, 85, 40],
      fill: false
    }],
    lineAtIndex: 2
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

Leave a comment