Display one label of the sum of stacked bars
See original GitHub issueHi,
I have a horizontal stacked bar chart which looks like this:
And I would like to display the sum of each stacked bar, like so:
I managed to get this result by returning an empty string for datasets that are not the last one (datasetIndex
), and computing the sum for each bar (dataIndex
):
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets; // Tried `.filter(ds => !ds._meta.hidden);` without success
if (ctx.datasetIndex === datasets.length - 1) {
let sum = 0;
datasets.map(dataset => {
sum += dataset.data[ctx.dataIndex];
});
return sum.toLocaleString(/* ... */);
}
else {
return '';
}
},
anchor: 'end',
align: 'end'
}
}
It works great, but if I toggle off one dataset (via the chart’s legend), the result is less great:
-
if I toggle off the first dataset, I still have the sum of the two datasets as a label:
-
if I toggle off the last dataset, I don’t have a label anymore:
As I commented in my code snippet, I tried to filter out the datasets with the _meta.hidden
metadata, but it seems that the formatter
function is not called again when toggleing datasets via the chart’s legend.
Is there a better way to use datalabels with stacked bar charts? Or does anyone have an idea to make it work?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:16 (4 by maintainers)
Top GitHub Comments
I think I would move the summation logic into a separated plugin responsible to compute the total for each “stack” and the utmost dataset index, the one for which you want to display the label. It would happen only one time, before the chart update (better for performances):
Then you need to register this plugin to the charts you want to display the total:
At this point, you can access computed information from
chart.$totalizer
and thus configure the datalabels plugin easily:Note that it’s better to hide the other labels using the
display
option because nothing else will be computed for this label (e.g. theformatter
will not be called for hidden labels).Fiddle: https://jsfiddle.net/simonbrunel/9ezggxx5/
This example doesn’t take in account all use cases, such as grouped stacks or negative values.
I know this is an old topic, but I modified Simon’s plugin to be usable for grouped stacks. Hope this helps anyone.
The totals are then callable by using
chart.$totalizer.totals[dataIndex][stack]
and the utmost items are callable by usingchart.$totalizer.utmost[stack]