Search code examples
javascripthtmlgraphchart.js

ChartJS: Grouped Stacked Bar Chart not Grouping


I am trying to create a grouped, stacked bar chart in ChartJS. For the below code, all works fine apart from the grouping aspect, it simply stacks all datasets on top of one another.

stackedBarChartData = {
        barPercentage: 1.0,
        //labels: stackedBarData['skills'],
        labels: ['1', '2', '3', '4', '5', '6', '7', '8'],
        datasets:[
            {
              label: 'Dataset 1',
              data: [0, 1, 3, 4, 2, 4, 5, 9],
              backgroundColor: '#D6E9C6',
              stack: 'Stack 0',
            },
            {
              label: 'Dataset 2',
              data: [0, 12, 3, 6, 2, 4, 8, 9],
              backgroundColor: '#FAEBCC',
              stack: 'Stack 0',
            },
            {
              label: 'Dataset 3',
              data: [0, 1, 3, 4, 2, 4, 5, 9],
              backgroundColor: '#EBCCD1',
              stack: 'Stack 1',
            },
        ]
    }
groupedChartOptions = {
    type: 'bar',
    data: stackedBarChartData,
    options: {
        scales: {
            scaleShowValues: true,
            xAxes: [{
                stacked: true,
                scaleLabel: {
                    display: true,
                    labelString: options.xLabel
                },
                ticks: {
                    autoSkip: false
                },
                gridLines: { display: false }
            }],
            yAxes: [{
                stacked: true,
                scaleLabel: {
                    display: true,
                    labelString: options.yLabel
                },
                gridLines: { display: false }
            }]
        },
        title:{
            display: true,
            text: options.title
        }
    }
}
return new Chart(chartObject, chartOptions);

The result is as follows:

enter image description here

Any help would be much appreciated.


Solution

  • The config you are using should work, the reason it not working is likely to be your verry outdated version of Chart.js. I suspect you are still using version 2.4.0. If you upgrade to 2.9.4 it will work

    https://jsfiddle.net/Leelenaleee/6h2ey8mu/8/