0👍
You can use for loops to calculate the sum simply as follows:
( or working example: codepen )
<script>
const ctx = document.getElementById('myChart');
const chartData = {
labels: [
"April",
"Mai",
"Juni",
"Juli",
],
datasets: [{
label: "black",
backgroundColor: "black",
data: [0, 20, 0, 20],
stack: 'combined',
type: 'bar'
}, {
label: "red",
backgroundColor: "red",
data: [0, 0, 0, 25],
stack: 'combined',
type: 'bar'
},
{
label: "green",
backgroundColor: "green",
data: [10, 20, 10, 25],
stack: 'combined',
type: 'bar'
},
],
}
var lineData = {
label: "line",
backgroundColor: "blue",
data: [],
borderColor: "blue",
// stack: 'combined',
type: 'line',
tension: 0,
}
for (let i = 0; i < chartData.datasets[0].data.length; i++) {
let sum = 0 //or 10
for (let j = 0; j < chartData.datasets.length; j++) {
sum += chartData.datasets[j].data[i]
}
lineData.data.push(sum)
}
chartData.datasets.unshift(lineData)
console.log(chartData)
new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
plugins: {
title: {
display: true,
text: "dvtq chart",
position: "top",
align: "start",
font: {
size: 20,
weight: "bold",
},
},
},
responsive: true,
maintainAspectRatio: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
},
},
},
});
</script>
- Chartjs-Catch event of show and hide dataset at chart.js
- Chartjs-Using string list as Chart.js label
Source:stackexchange.com