1

I'm trying to create a bar and line chart using Chart.js, but I wanted to bar chart to have a different set of 'labels'.

the data for the line chart is on the first and last point [2800, 1300] and I wanted the line to draw across the labels of the bar chart.

Is this possible?

Expected enter image description here

Result enter image description here

watcher
  • 83
  • 2
  • 7

2 Answers2

3

I was able to solve this by extending Chartjs.

var originalLineDraw = Chart.controllers.bar.prototype.draw;
Chart.helpers.extend(Chart.controllers.bar.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'];

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(xaxis.getPixelForValue(undefined, 0), yaxis.getPixelForValue(70));
      ctx.strokeStyle = '#000000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, 7), yaxis.getPixelForValue(10));
      ctx.stroke();
      ctx.restore();
    }
  }
});

var config = {
  type: 'bar',
  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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myChart"></canvas>
watcher
  • 83
  • 2
  • 7
0

https://jsfiddle.net/fgx92Lm5/

The data for the line should be:

data: [2800,2680,2565,2450,2335,2220,2105,1990,1875,1760,1645,1530,1415,1300]

in other words, you need to calculate the other values based on the end points and based on the number of the bars in such a way to obtain a line.

delta = (2800 - 1300) / 13 =~ 115

Alex Baban
  • 11,312
  • 4
  • 30
  • 44