问题描述
我正在构建一系列甜甜圈图,我想删除图例中的第二个项目,因此,当我使用generateLegend()方法生成图例时,我只想获取第一个值.
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.
在文档中,有一个选项读取
但是我找不到如何使用它的示例.在此笔中,您可以看到中间的2个标签,我只想显示第一个标签.我尝试了不同的方法,但没有成功.只是删除该项目对我不起作用,因为< li>
项仍然存在.这是我正在使用的代码.
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();
提前感谢任何指针.
推荐答案
filter函数的工作原理与Javascript的本机 Array.prototype.filter
完全相同.因此,如果要在特定索引处显示图例,只需返回true.
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.
编辑:过滤器函数位于 labels
字段内.
The filter function would come inside the labels
field.
legend: {
display: true,
labels: {
filter: function(legendItem, data) {
return legendItem.index != 1
}
}
}
这篇关于使用Chartjs.org V2.7过滤图例项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!