Filter a legend Item with Chartjs.org V2.7

10,156

The filter function works exactly like the Javascript's native Array.prototype.filter. So just return true if you want to show the legend at a particular index.

EDIT: The filter function would come inside the labels field.

 legend: {
      display: true,
      labels: {
           filter: function(legendItem, data) {
                return legendItem.index != 1 
           }
      }
 }
Share:
10,156
ryangus
Author by

ryangus

Sono un progettista web & grafico, amante della tecnologia, appassionato di semplificare le metodologie.

Updated on June 16, 2022

Comments

  • ryangus
    ryangus almost 2 years

    I am building a series of doughnut charts and I would like to remove the second item in the legend, so when I generate the legend with the generateLegend() method I just want to get the first value.

    In the documentation there is an option that reads

    Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data

    But I can't find an example how to use it. In this Pen you can see the 2 labels in the middle, I just want to show the first label. I tried different approaches with no success. Just deleting the item doesn't work for me because the <li> item still there. Here's the code I am using.

    $id = function(id) {
      return document.getElementById(id);
    };
    
    var langDataEs = {
      type: "doughnut",
      data: {
        datasets: [
          {
            data: [75, 25],
            backgroundColor: ["#8dc63f", "#1d1d1d"]
          }
        ],
        labels: ["es", "learning"]
      },
      options: {
        legend: {
          display: false,
          /* I would like to remove the item "learning" */
          filter: function() {
    
          },
        },
        responsive: true
      }
    };
    
    langChartEs = new Chart($id("langEs").getContext("2d"), langDataEs);
    $id("es").innerHTML = langChartEs.generateLegend();
    

    Thanks in advance for any pointers.

    • ryangus
      ryangus over 6 years
      OMG, I was so focused on doing it vía JavaScript that I never thought about CSS, I'll just hide the second child for now, I won't accept your answer just yet to see if someone can came up with a JavaScript solution just to learn, thanks so much.
  • ryangus
    ryangus over 6 years
    I tried here as you sugested but it doesn't seems to work for me or I am doing it wrong...
  • dsaket
    dsaket over 6 years
    Sorry...my bad. Check my edited version! Hope it works.
  • dsaket
    dsaket over 6 years
    Also it's legendItem.index instead of legendItem.datasetIndex
  • Davie
    Davie over 5 years
    because the filter function is called for each series of data