42

Is it possible to only hide certain dataset legends in chartjs? I know it is possible to hide all with

options: {
    legend: {
        display: false
1
  • I am not sure it is just depending on the version. In my case, this works perfectly in version 2.x.
    – Steven T.
    Nov 20, 2020 at 4:10

5 Answers 5

75

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.

3
  • 2
    I had to add an extra tidbit to the filter function to check the item.text for undefined. So my function returned: return item.text == null || !item.text.includes('label to remove');
    – JED
    Feb 8, 2019 at 19:29
  • I adjusted this a little so now it works without relying on labels: stackoverflow.com/a/64628918/2566029 Nov 2, 2020 at 16:04
  • 1
    At present (Chartjs 3.7), the item object passed to the filter function contains a datasetIndex field that is probably preferable to using labels (since those are liable to be localised anyway). Feb 6, 2022 at 2:53
4

Update for Chart.js 3.x

This solution still works, but legend options have been placed inside "plugins". So, if you have a dataset whose label you don't want to appear on the legend, give it a specific name, like label: "none", for example, and then use the filter function:

    options: {
        plugins: {
            legend: {
                labels: {
                    filter: item => item.text !== 'none'
                }
            }
        }
    }
0
3

First No official example of this issue under chart.js docs.

How to filter by value (Hide all legends for a value greater than 1000)

Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data. https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration

basic example - "works like magic":

Data:

  var data = {
    labels: ["Africa", "Asia", "Europe"],
    datasets: [{
      label: "Population (millions)",
      backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
      data: [1000,1500,2000]
    }]
  };

The "trick" - get the array of values:

data.datasets[0]

Like this i get the data array.

Next - The filter loop throw data - Each time i get the current value by index. Basic Array idea: How to get value at a specific index of array In JavaScript?

var index = legendItem.index; /* 0..1...2 */
var currentDataValue =  data.datasets[0].data[index]; /* 1000...1500...2000 */

if "consept"

Show all legends:

if (true){
  return true;
}

And this hide all legends

if (false){
  return true;
}

So add any if statement you want (data value in our case):

if (currentDataValue > 1000){
  return true;
}

Complete example:

Hide legend if the value is greater than 1,000:

var data = {
  labels: ["Africa", "Asia", "Europe"],
  datasets: [{
    label: "Population (millions)",
    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
    data: [1000,1500,2000]
  }]
};

var options = {
  responsive: true,
  title: {
    text: 'Hide africa legened (Greater than 1000)',
    position: 'top',
    display: true
  },
  legend: {
    display: true,
    labels: {
      /* filter */
      filter: function(legendItem, data) {
        /* filter already loops throw legendItem & data (console.log) to see this idea */
        var index = legendItem.index;
        var currentDataValue =  data.datasets[0].data[index];
        console.log("current value is: " + currentDataValue)
        if (currentDataValue > 1000)
        {
          return true; //only show when the label is cash
        }
      },
      /* generateLabels */
      generateLabels(chart) {
        const data = chart.data;
        if (data.labels.length && data.datasets.length) {
          /* inner loop throw lables */
          return data.labels.map((label, i) => {
            var backgroundColor = data.datasets[0].backgroundColor[i];
            return {
              text: label + " | " + data.datasets[0].data[i],
              fillStyle: backgroundColor,
              // Extra data used for toggling the correct item
              index: i
            };
          });
        }
        return [];
      }

    },

  },
  scales: {
    xAxes: [{
      display: true
    }],
    yAxes: [{
      display: true
    }]
  }
};


new Chart(document.getElementById("chart"), {
  type: 'pie',
  data: data,
  options: options
});
<canvas id="chart" width="800" height="450"></canvas>
   
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

By the way in the example above i also use generateLabels idea (Add the value next to label text).

2
  • 1
    In case .index is undefined, try .datasetIndex.
    – ddc
    Aug 25, 2021 at 16:04
  • Is it possible to hide certain data points(circle) on line too with the help of filter?
    – Volatil3
    Jan 31 at 7:37
2

In my case, changing the label to "hidden" caused that to show in the tooltip, instead of the text I wanted.

So here's a way you can target each dataset's legend by it's index number without changing the label!

const chart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    legend: {
      labels: {
        filter: function(item, chart) {
          return item.datasetIndex !== INDEX_OF_DATASET && item.datasetIndex !== INDEX_OF_ANOTHER_DATASET;
        }
      }
    }
  }
});

In my case, I'm using wpDataTables to create a chart in WordPress, so the code looks like this:

wpDataChartsCallbacks[INDEX_OF_CHART_HERE] = function (obj) {
  obj.options.options.legend.labels.filter = function(item, chart) {
    return item.datasetIndex !== INDEX_OF_DATASET && item.datasetIndex !== INDEX_OF_ANOTHER_DATASET;
  }
}

It's working great for me!

2

**You can use something like this to filter out legends in your chart: **

plugins: {
  legend: {
    labels: {
      filter: function( item, chart){                   
        if (item.text == 'Open' || item.text == 'High') {
          return false;
        }else{
          return item;
        }
      }
    }
  },
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.