1👍
✅
Basically your question is two parts.
- Filter the 0 values
- Add accumulative sum to each datapoint in tooltip
I simplified your code as you had a for loop which was not needed as it could be done all in Chart JS tooltip.
I created a video with the entire breakdown and explanation. You can watch here for more understanding: ChartJS: Adjust Tooltip with sums in body
See code below:
<script>
// setup
const data = {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},{
label: '# of Cost',
data: [11, 4, 0, 7, 10, 13],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},{
label: '# of Sales',
data: [10, 0, 10, 0, 10, 22],
backgroundColor:
'rgba(255, 206, 86, 0.2)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}]
};
// tooltip block
const tooltip = {
yAlign: 'bottom',
filter: function filterZeroData(datapoint) {
return datapoint.raw > 0;
},
callbacks: {
label: function(context) {
const stackedBarArray = [];
for (i = 0; i <= context.datasetIndex; i++){
stackedBarArray.push(context.parsed._stacks.y[i]);
};
console.log(stackedBarArray);
// reduce array
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// return value in tooltip
console.log(context.dataset.label)
const labelName = context.dataset.label;
const labelValue = stackedBarArray.reduce(reducer);
return `${labelName} ${labelValue}`;
}
}
};
// config
const config = {
type: 'bar',
data,
options: {
plugins: {
tooltip,
},
scales: {
x: {
stacked: true
},
y: {
stacked: true,
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
Source:stackexchange.com