【问题标题】:chartjs: How to remove specific labelchartjs:如何删除特定标签
【发布时间】:2025-11-24 07:40:02
【问题描述】:

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

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
});

结果图是这样的:

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

【问题讨论】:

    标签: javascript jquery bar-chart chart.js


    【解决方案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>

    【讨论】: