score:1

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 => {
                    return item.text != "none"
                }
            }
        }
    }
}

score:2

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).

score: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!

score: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;
        }
      }
    }
  },
}

score:72

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.


Related Query

More Query from same tag