2👍
You can set a Tooltip filter. Make a simple function that only returns the label/value when the value is nonzero.
import Chart from 'chart.js';
var ctx = document.getElementById('mychart');
var data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
datasets: [{
label: 'Label Title',
data: [0, 0, 0, 1, 2, 3, 5],
}]
};
var barChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
x: {stacked: true},
y: {stacked: true},
},
tooltips: {
filter: function (tooltipItem, data) {
// data contains the charts data, make sure you select the right
// value.
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
if (value === 0) {
return false;
} else {
return true;
}
}
}
}
}
https://www.chartjs.org/docs/latest/configuration/tooltip.html
https://www.chartjs.org/docs/latest/configuration/tooltip.html#filter-callback
So, in other words, you need to change your getChartOptions()
:
getChartOptions(): import('chart.js').ChartOptions | undefined {
return {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked',
},
tooltips: {
mode: 'index',
intersect: false,
filter: function (tooltipItem, data) {
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
if (value === 0) {
return false;
} else {
return true;
},
},
},
responsive: true,
scales: {
xAxes: [
{
stacked: true,
},
],
yAxes: [
{
stacked: true,
},
],
},
};
}
2👍
I’m not sure if this is new, as I just started using chart.js 4.3.0
.
I was able to filter on the .raw
key, which holds the item count.
tooltip: {
filter: (tooltipItem) => tooltipItem.raw > 0,
}
- [Chartjs]-Chart.js: only show labels on x-axis for data points
- [Chartjs]-Chart.js get array of currently visible points on graph
Source:stackexchange.com