Chartjs-How to display grouped bar chart using chart.js?

0👍

There are two problems in your code.

First you don’t correctly retrieve the 2D-Context.

var ctx = document.getElementById('barChart').getContext('2d');

Further you have some strange apostrophes that need to be changed.

Please have a look at your amended code below.

var lbls = ['Selling', 'Cost', 'Gross'];
var curYearData = [2345, 1234, 1111];
var preYearData = [3456, 2345, 1111];

var ctx = document.getElementById('barChart').getContext('2d');
var barChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: lbls,
    datasets: [{
        label: '2020',
        data: curYearData,
        backgroundColor: 'blue',
      },
      {
        label: '2019',
        data: preYearData,
        backgroundColor: 'red',
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="barChart"></canvas>

Leave a comment