在chartjs中是否可以隐藏某些数据集图例? [英] Is it possible in chartjs to hide certain dataset legends?

查看:585
本文介绍了在chartjs中是否可以隐藏某些数据集图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅在chartjs中隐藏某些数据集图例?我知道可以用

Is it possible to only hide certain dataset legends in chartjs? I know it is possible to hide all with

options: {
    legend: {
        display: false

推荐答案

简短的回答:是可能的.不幸的是,它并不像开发人员所能做到的那样简单.

Short answer: Yes it is possible. Unfortunately it's not quite as simple as the developers could make it.

如果您知道图例中显示的项目的text值是什么,则可以将其过滤掉.阅读Chart.js文档后,我发现了传奇标签配置,其中详细介绍了filter函数,该函数可用于过滤出图例项",尽管此函数必须在父图表选项对象上设置,而不是在数据集本身上设置: >

If you know what the text value of the item being displayed in the legend is, then you can filter that out. After reading through the Chart.js docs I found the section Legend Label Configuration that details a filter function that can be used to "filter out the legend items", although this function must be set on the parent chart options object, not as an option on the dataset itself:

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            labels: {
                filter: function(item, chart) {
                    // Logic to remove a particular legend item goes here
                    return !item.text.includes('label to remove');
                }
            }
        }
    }
});

现在,每次数据更改并通过chart.update()更新图表时都会出现此调用函数.

Now it appears each time the data changes and the chart is updated via chart.update() this filter function is called.

为方便起见,我在 jsfiddle 中进行了设置.

For convenience I have set this up in a jsfiddle for you to play with.

注意:此解决方案是围绕ChartJS 2.7.1版的API设计的.将来的版本可能会改善对数据集图例标签的控制.

Note: This solution was designed around the API for version 2.7.1 of ChartJS. Future versions may improve the control over dataset legend labels.

这篇关于在chartjs中是否可以隐藏某些数据集图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆