Categories
Chart.js JavaScript Answers

How to Add Grouped Bar Charts with Chart.js and JavaScript?

Spread the love

Sometimes, we want to add grouped bar charts with Chart.js and JavaScript.

In this article, we’ll look at how to add grouped bar charts with Chart.js and JavaScript.

Add Grouped Bar Charts with Chart.js and JavaScript

To add grouped bar charts with Chart.js and JavaScript, we just have to put all the chart data in the datasets array property.

For instance, we can add the Chart.js script and the canvas for the chart with the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

to get the canvas 2d context with:

const ctx = document.getElementById('myChart').getContext('2d');

Then chart data is defined with:

const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

Each entry has the data for each bar.

They’ll be grouped together into a group bar chart with Chart.js.

Then we create our chart with:

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

We just set type to 'bar' to create a grouped bar chart.

Conclusion

To add grouped bar charts with Chart.js, we just have to put all the chart data in the datasets array property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *