How to add a dataset to the stacked bar in chart.js?

by wilmer.lemke , in category: Javascript , 8 months ago

How to add a dataset to the stacked bar in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 8 months ago

@wilmer.lemke 

To add a dataset to a stacked bar chart in Chart.js, you need to modify the data object in the chart configuration. Here's an example of how to do it:

  1. First, create a new dataset by adding an object to the datasets array in the data object. Each dataset will represent a different stacked bar in the chart.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var data = {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [
        {
            label: 'Dataset 1',
            data: [10, 20, 30, 40, 50],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        },
        {
            label: 'Dataset 2',
            data: [20, 30, 40, 50, 60],
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
        }
    ]
};


  1. Add the new dataset to the datasets array in the chart configuration. Make sure to update the labels array if needed to match the number of items in the new dataset.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        scales: {
            x: {
                stacked: true,
            },
            y: {
                stacked: true
            }
        }
    }
});


  1. Render the chart and you should see the new dataset added as a stacked bar on top of the existing bars.


By following these steps, you can easily add a dataset to a stacked bar chart in Chart.js.