chartjs:如何删除特定标签

时间:2017-05-22 14:08:39

标签: javascript jquery bar-chart chart.js

我有一个包含这些数据和选项的条形图:

var data = {
    labels: periodnames,
    datasets: [          
        {
            yAxisID: "bar-stacked",
            data: rcash,
            backgroundColor: "#FFCE56",                  
            label:""
        },
    {
        yAxisID:"bar-stacked",
        data: pcash,
        backgroundColor: "#FFCE56",
        label: "cash"           

    }       

    ]

};

var options = {        
    animation: {
        animateScale: true
    },        
    scales: {
        xAxes: [{
        stacked: true,
    }],        
        yAxes: [ 
            {
                display:false,
                id: "line-axis",                  

            },
            {
            id: "bar-stacked",
            stacked: true,                

        }            
        ]
    }
}

finactivityGraphChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
});

结果图表如下: enter image description here

我的问题是我不想显示第一个数据集的标签。如果我没有定义它,它会在旁边显示黄色框,其值为“undefine”。我想我必须修改Chart.js文件。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

可以使用图例标签的filter功能来实现。

请参阅Legend Label Configuration

简而言之,在图表选项中添加以下内容......

legend: {
   labels: {
      filter: function(label) {
         if (label.text === 'cash') return true;
      }
   }
},

<强>ᴅᴇᴍᴏ

var ctx = document.querySelector('#c').getContext('2d');
var data = {
   labels: ['Jan', 'Feb', 'Mar'],
   datasets: [{
      yAxisID: "bar-stacked",
      data: [1, 2, 3],
      backgroundColor: "#FFCE56",
      label: "gold"
   }, {
      yAxisID: "bar-stacked",
      data: [-1, -2, -3],
      backgroundColor: "#FFCE56",
      label: "cash"
   }]
};
var options = {
   legend: {
      labels: {
         filter: function(label) {
            if (label.text === 'cash') return true; //only show when the label is cash
         }
      }
   },
   animation: {
      animateScale: true
   },
   scales: {
      xAxes: [{
         stacked: true,
      }],
      yAxes: [{
         display: false,
         id: "line-axis",
      }, {
         id: "bar-stacked",
         stacked: true,
      }]
   }
}
finactivityGraphChart = new Chart(ctx, {
   type: 'bar',
   data: data,
   options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="c"></canvas>