Chart.js
Chart.js copied to clipboard
[FEATURE] Display stack label for Stacked groups
Feature Proposal
When I use stacked groups, I want the possibility to display stack label if correct option is selected.
Suggestions of options:
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: this.barChartLabels,
datasets: this.datasets;
},
options: {
scales: {
xAxes: [{
display: true,
stacked: barStacked,
displayStackLabel: true
}],
yAxes: [{
display: true,
stacked: barStacked
}],
}
}
});
Feature Use Case
I have found a stack-overflow with exactly the same feature wanted : https://stackoverflow.com/questions/48643408/chart-js-grouped-sub-labels
+1
+1
+1
is this released yet? where can I find this documentation?
+1 Just came here looking for same feature. Group / sub-group labels.
+1 searching around for this!
+1 need this
+1 Would like this
This is actually resolved using datalabels plugin, and labels. Use labels as regular maybe adjusting vertical height to make room for datalabels. Also adjust datalabels vertical height and offset then use formatter
chartSettings.options.plugins.datalabels.formatter = function (value, context) {
let ds = context.chart.data.datasets
// check if it's the first ds
if (ds[context.datasetIndex - 1]) {
// check if the ds is in the same stack as the ds before
if (ds[context.datasetIndex - 1].stack == ds[context.datasetIndex].stack) {
return ''
} else {
return ds[context.datasetIndex].stack;
}
} else {
return ds[context.datasetIndex].stack;
}
Stumbled across this issue and found @kpetrow solution quite interesting. I've improved it to display the last series' label on stack, like this:
The original proposal was to display it below the series, I know. But displaying it above is simpler and also prevents the user from getting confused with the X axis.
Under the hood:
formatter: (value, context) => {
const { datasets } = context.chart.data;
const stacksCount = Object.keys(context.chart._stacks).length;
if (context.datasetIndex > datasets.length - 1 - stacksCount) {
return datasets[context.datasetIndex].stack;
} else {
return '';
}
}
A working example can be found at https://codepen.io/jlozovei/details/NWJpYvy :sparkles: