如何在Chartjs上隐藏多个图例?

时间:2019-01-24 12:57:50

标签: javascript chart.js

如何使用Chart js隐藏图表上的两个标签?

以该代码为例,我想隐藏图例1和图例2,但我只能隐藏一个元素

const ctx = document.getElementById('chart');
const data = [1, 2, 3, 4, 5, 6, 7, 8];
const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      // This label is removed in the filter function
      label: 'Legend 1',
      data: [12, 19, 3, 5, 2, 3],
    }, {
      label: 'Legend 2',
      data: [11, 12, 33, 4, 2, 3],
    }, {
      label: 'Legend 3',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgba(0, 195, 255, 0.2)',
    }]
  },
  options: {
    legend: {
      labels: {
        filter: function(item, chart) {
          // Logic to remove a particular legend item goes here
                    return !item.text.includes('Legend 1');
        }
      }
    }
  }
});

谢谢

编辑1

需要明确的是,我已经找到了只隐藏一个图例的方法,但是我想隐藏多个图例。

像下面的图像 enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

与其在选项级别隐藏它们,不如在标签级别隐藏它们:

    datasets: [{
      label: 'Legend 1',
        hidden: true,
      data: [12, 19, 3, 5, 2, 3],
    }, {
      label: 'Legend 2',
      hidden: true,
      data: [11, 12, 33, 4, 2, 3],

答案 1 :(得分:0)

this link

找到了答案

基本上我要做的是在选项上插入以下语句:

    legend: {
        labels: {
            filter: function(legendItem, chartData) {
                if (legendItem.datasetIndex === 0 || legendItem.datasetIndex === 1 ) {
                    return false;
                }
            return true;
            }
        }
},   

我相信这解决了我的问题