Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar Chart Not Stacking When Using ChartJs

Tags:

chart.js

I'm trying to create a stacked bar chart (vertical or horizontal), using chartJs. Having followed their documentation and tried various solutions here on SO, but I still can not get the values to stack.

const ctx = document.getElementById('chart-canvas').getContext('2d');
const chartCanvas = () => {
   
const chart = new Chart(ctx, {

    type: 'bar',
    // The data for our dataset
    data: {
        labels: ['a', 'b', 'c'],
        datasets: [{
            label: 'some title here',
            data: [49999,20000,35000], 
            backgroundColor: ['rgba(255, 99, 132, .5)','rgba(25, 99, 132, .5)','rgba(255, 9, 12, .5)'],
            borderColor:     ['rgb(255, 99, 132)','rgb(25, 99, 132)','rgb(255, 9, 12)'],
        }]
    },

    // Configuration options go here
    options: {
        scales: {
            xAxes: [{ stacked: true }],
            yAxes: [{ stacked: true }]
        },
        legend: {
            display: false,
        },
        maintainAspectRatio: false,
    }
});
}
chartCanvas()

I have created a fiddle https://jsfiddle.net/trig79/oxantepu/1/

appreciate any guidance on where I am going wrong

like image 300
trig79 Avatar asked Mar 16 '26 19:03

trig79


1 Answers

Stacked option only works if you use multiple datasets. You can put each stacked value in a seperate dataset so you can stack them.

const ctx = document.getElementById('chart-canvas').getContext('2d');
const chartCanvas = () => {
   
const chart = new Chart(ctx, {

    type: 'bar',
    // The data for our dataset
    data: {
        labels: ['First Data'],
        datasets: [
            {
                label: 'a',
                data: [49999], 
                backgroundColor: ['rgba(255, 99, 132'],
                borderColor:     ['rgb(255, 99, 132)'],
            },
            {
                label: 'b',
                data: [20000], 
                backgroundColor: ['rgba(25, 99, 132, .5)'],
                borderColor:     ['rgb(25, 99, 132)'],
            },
            {
                label: 'c',
                data: [35000], 
                backgroundColor: ['rgba(255, 9, 12, .5)'],
                borderColor:     ['rgb(255, 9, 12)'],
            }
        ]
    },

    // Configuration options go here
    options: {
        scales: {
            xAxes: [{
              stacked: true
            }],
            yAxes: [{
              stacked: true
            }]
          },
        legend: {
            display: false,
        },
        maintainAspectRatio: false,
    }
});
}
chartCanvas()
like image 63
Juha Kangas Avatar answered Mar 22 '26 16:03

Juha Kangas