Chartjs-Aligning linechart with grouped-barchart using chart.js

0👍

You could use a custom plugin to move the points of line dataset to the same offset of the bar dataset.

See snippet:

const plugin = {
  id: 'alignLine',
  beforeDraw(chart) {
    const metabar = chart.getDatasetMeta(0);
    const metaline = chart.getDatasetMeta(2);
    const n = metabar.data.length;
    for (let i=0; i<n; i++) {
      const databar = metabar.data[i];
      const dataline = metaline.data[i];
      dataline.x = databar.x;
    }
  }
}
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  plugins: [plugin],
  data: {
    labels: ['1', '2', '3', '4', '5', '6', '7'],
    datasets: [{
      data: [12, 19, 3, 5, 2, 3, 14],
    }, {
      data: [12, 19, 3, 5, 3, 3, 10],
    }, {
      type: 'line',
      data: [16, 21, 5, 3, 10, 23,23],
    }],
  },
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/chart.umd.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment