Categories
JavaScript Answers

How to add a grouped bar charts in chart.js and JavaScript?

Spread the love

Sometimes, we want to add a grouped bar charts in chart.js and JavaScript.

In this article, we’ll look at how to add a grouped bar charts in chart.js and JavaScript.

How to add a grouped bar charts in chart.js and JavaScript?

To add a grouped bar charts in chart.js and JavaScript, we add the data for each bar in the chart.

For instance, 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,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [
        {
          ticks: {
            min: 0,
          },
        },
      ],
    },
  },
});

to set data as the value of the data property in the object we call the Chart constructor with.

And we set the type to 'bar' so that the data will be rendered as a grouped bar chart.

Conclusion

To add a grouped bar charts in chart.js and JavaScript, we add the data for each bar in the chart.

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 *