Filter a legend Item with Chartjs.org V2.7

2019-07-24 07:55发布

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.

1条回答
叼着烟拽天下
2楼-- · 2019-07-24 08:27

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 
           }
      }
 }
查看更多
登录 后发表回答