2👍
✅
This can be done using the Plugin Core API. It offers different hooks that can be used to perform custom code.
- The
labels
anddata
need to be defined outside the chart configuration. - In the
beforeUpdate
hook, you set the initiallabels
anddata
to the chart configuration. - In the
beforeElementsUpdate
hook you remove individuallabels
and correspondingdata
values from the chart configuration if all values for a certain label arenull
or if thedataset
ishidden
.
Please take a look at below runnable sample and see how it works.
const labels = ['A', 'B', 'C'];
const data = [
[10, null, 4],
[9, null, 8],
[3, 5, 8]
];
new Chart('chart', {
type: 'bar',
plugins: [{
beforeUpdate: chart => {
chart.data.labels = labels;
chart.data.datasets.forEach((ds, i) => ds.data = data[i]);
},
beforeElementsUpdate: chart => {
let sums = labels.map((l, i) => chart.data.datasets.reduce((prev, ds, iDs) => prev + (chart.getDatasetMeta(iDs).hidden ? 0 : ds.data[i]), 0));
chart.data.labels = labels.filter((l, i) => sums[i]);
chart.data.datasets.forEach((ds, iDs) => ds.data = data[iDs].filter((v, i) => sums[i]));
}
}],
data: {
datasets: [{
label: 'Dataset 1',
backgroundColor: 'red'
},
{
label: 'Dataset 2',
backgroundColor: 'blue'
},
{
label: 'Dataset 3',
backgroundColor: 'green'
}
]
},
options: {
indexAxis: 'y',
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<canvas id="chart" height="80"></canvas>