1π
β
If you want to use object notation you also have to provide the right x label to chart.js. Also you canβt use a dynamic key, your data must be in the same key.
const dat = {
"1980": {
"legal": {
"departments": 1,
"Foreign Agency": 3,
Corporation: 3
},
x: "1980"
},
"1981": {
"legal": {
"departments": 2,
"Foreign Agency": 2,
Corporation: 5
},
x: "1981"
},
"1982": {
"legal": {
"departments": 3,
"Foreign Agency": 1,
Corporation: 8
},
x: "1982"
}
};
const data1 = {
datasets: [{
label: 'Department number',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: Object.values(dat),
parsing: {
yAxisKey: 'legal.departments'
}
}]
};
const config1 = {
type: 'bar',
data: data1,
options: {
plugins: {
title: {
display: true,
text: 'Stacked Bar Chart of legal entities 1980-1982'
},
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
};
const myChart1 = new Chart(
document.getElementById('myChart1'),
config1
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<canvas id="myChart1"></canvas>
You can also make map all the data to a single array beforehand and provide that:
const labels = [
'1980',
'1981',
'1982'
]
const dat = {
"1980": {
"legal": {
"departments": 1,
"Foreign Agency": 3,
Corporation: 3
},
x: "1980"
},
"1981": {
"legal": {
"departments": 2,
"Foreign Agency": 2,
Corporation: 5
},
x: "1981"
},
"1982": {
"legal": {
"departments": 3,
"Foreign Agency": 1,
Corporation: 8
},
x: "1982"
}
};
const values = Object.values(dat).map(e => (e.legal.departments))
const data1 = {
labels: labels,
datasets: [{
label: 'Department number',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: values
}]
};
const config1 = {
type: 'bar',
data: data1,
options: {
plugins: {
title: {
display: true,
text: 'Stacked Bar Chart of legal entities 1980-1982'
},
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
};
const myChart1 = new Chart(
document.getElementById('myChart1'),
config1
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<canvas id="myChart1"></canvas>
Source:stackexchange.com