我试图隐藏项目的图例标题(如果它的值为零)。这里存在类似的问题,但没有解决我的问题。
下面是我的源代码:
<script>
var ctx = document.getElementById('beratungsfelderChart');
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'],
datasets: [{
label: '# of Votes',
data: [0, 3, 3, 5, 2],
backgroundColor: [
'#172b4dD9',
'#2dce89D9',
'#231F20D9',
'#192d35D9',
'#3B6058D9'
]
}]
},
options: {
legend: {
labels: {
//filter: function(item, chart, context) {
// return !item.text.includes('Test');
//}
filter: function(item, context) {
return !context.dataset.data[context.dataIndex] == 0;
}
}
},
axis: {
scales: {
yAxes: [{
display: false
}],
xAes: [{
ticks: {
display: false
}
}]
}
},
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] > 1;
}
}
}
}
});
</script>
如您所见,我尝试了一些可能的解决方案,但不幸的是,到目前为止,没有任何结果。
1.选项->图例->标签
2. 选项 -> 插件 -> 数据标签
我希望有人能以某种方式帮助我。
最好, 纳德
最佳答案
您应该使用legend.labels.filter
如下。
legend: {
labels: {
filter: (legendItem, data) => data.datasets[0].data[legendItem.index] != 0
}
}
new Chart(document.getElementById('beratungsfelderChart'), {
type: 'doughnut',
data: {
labels: ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'],
datasets: [{
label: '# of Votes',
data: [0, 3, 3, 5, 2],
backgroundColor: [
'#172b4dD9',
'#2dce89D9',
'#231F20D9',
'#192d35D9',
'#3B6058D9'
]
}]
},
options: {
legend: {
labels: {
filter: (legendItem, data) => data.datasets[0].data[legendItem.index] != 0
}
},
axis: {
scales: {
yAxes: [{
display: false
}],
xAes: [{
ticks: {
display: false
}
}]
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="beratungsfelderChart" height="90"></canvas>
关于javascript - 如果图例文本为零,如何隐藏它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60440032/