Filter a legend Item with Chartjs.org V2.7

时光总嘲笑我的痴心妄想 提交于 2019-12-24 00:38:38

问题


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:


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 
           }
      }
 }


来源:https://stackoverflow.com/questions/46374333/filter-a-legend-item-with-chartjs-org-v2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!