问题
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