ChartDataLabels Plugin - Total #415
Replies: 2 comments
-
I kind of gave up... no solution could really print label and total since the total is using the last position of the array... that's why in the video they removed the label and just displayed the total. This is what I got so far: `datalabels :{
|
Beta Was this translation helpful? Give feedback.
-
@Cezar-Duarte-UWT to have a total label on a stacked bar chart as you reported, you could use You need to create 2 labels, 1 for the values of each bar, and 1 for the total. datalabels: {
color: 'blue',
labels: {
total: { // <------------------- LABEL for TOTAL
font: {
weight: 'bold'
},
anchor: 'end',
align: 'top',
formatter: (value, context) => {
const datasetArray = [];
context.chart.data.datasets.forEach((dataset) => {
if (dataset.data[context.dataIndex] != undefined) {
datasetArray.push(dataset.data[context.dataIndex]);
}
});
function totalSum(total, datapoint) {
return total + datapoint;
}
let sum = datasetArray.reduce(totalSum, 0);
if (context.datasetIndex === datasetArray.length - 1) {
return sum;
} else {
return '';
}
}
},
value: { // <------------------- LABEL for BAR VALUE
color: 'black',
}
}
} Furthermore there was a bug in the datalabels format config you published: Your code: const datasetArray = [];
context.chart.data.datasets.forEach((dataset) => {
if (dataset.data[context.dataIndex] != undefined) {
datasetArray.push(dataset.data[0]);
}
}); The correct one: const datasetArray = [];
context.chart.data.datasets.forEach((dataset) => {
if (dataset.data[context.dataIndex] != undefined) {
datasetArray.push(dataset.data[context.dataIndex]);
}
}); I have reused your config (for total), see codepen: https://codepen.io/stockinail/pen/VYZQobQ Let me if it works for you as well. |
Beta Was this translation helpful? Give feedback.
-
Is there a way to display the total on top of the bar like this example https://support.aircall.io/hc/article_attachments/13207166053149 ?
I am using "chart.js": "^3.9.1", and I followed these instructions https://www.youtube.com/watch?v=mlOlkuuh_E8
But the total is messed up, it is not summarizing everything and it repeated the total at the top like 0140 for all bars..
The extra code per that video is:
datalabels : { anchor:'end', align:'top', formatter:(value, context) =>{ const datasetArray = []; context.chart.data.datasets.forEach((dataset) => { if(dataset.data[context.dataIndex] != undefined){ datasetArray.push(dataset.data[0]); } }); function totalSum(total, datapoint){ return total+datapoint; }//end totalSum let sum = datasetArray.reduce(totalSum, 0); if(context.datasetIndex === datasetArray.length-1){ return sum; }else{ return ''; } }//end formatter }//end datalabels
I also noticed if one of the stacked bars is returning 0 it prints the number one on top of the other so I have one bar with 14 and another one 0 I can see both numbers 14/0 mixed...
Beta Was this translation helpful? Give feedback.
All reactions