Is it possible in chartjs to hide certain dataset legends?

Short answer: Yes it is possible. Unfortunately it’s not quite as simple as the developers could make it.

If you know what the text value of the item being displayed in the legend is, then you can filter that out. After reading through the Chart.js docs I found the section Legend Label Configuration that details a filter function that can be used to “filter out the legend items”, although this function must be set on the parent chart options object, not as an option on the dataset itself:

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            labels: {
                filter: function(item, chart) {
                    // Logic to remove a particular legend item goes here
                    return !item.text.includes('label to remove');

Now it appears each time the data changes and the chart is updated via chart.update() this filter function is called.

For convenience I have set this up in a jsfiddle for you to play with.

Note: This solution was designed around the API for version 2.7.1 of ChartJS. Future versions may improve the control over dataset legend labels.

Leave a Comment