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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With