You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chart.js如何移除柱状图标题下方的多余标签

Chart.js柱状图标题下方多余标签移除方案

问题场景

使用Chart.js开发婚姻状态统计柱状图时,标题下方出现非预期多余标签,需要移除。

原有实现代码

//MARITAL STATUS 
var marital_status=obj.marital_status;
var ctx2 = document.getElementById('marital_status_chart').getContext('2d');
var myChart2 = new Chart(ctx2, {
    type: 'bar',
    data: {
        labels: ["Single","Married", "Widowed","Separated","Others"],
        datasets: [{
            data: [marital_status.Single, marital_status.Married, marital_status.Widowed,marital_status.Separated,marital_status.Others],
            borderWidth: 1,
            backgroundColor: my_backgroundColors,
            hoverBackgroundColor: my_hoverBackgroundColor,
            hoverBorderColor: my_hoverBorderColor,
        }]
    },
    plugins: [ChartDataLabels],
    options: {
        plugins: {
            datalabels: {
                color: 'black'
            },
            title: {
                display: true,
                text: 'Marital Status'
            }
        }
    }
});

实际运行效果

婚姻状态统计柱状图运行效果

问题原因

标题下方的多余元素是Chart.js默认开启的图例(legend)组件,当前图表仅包含单个数据集,无需图例展示,默认渲染规则下就会出现这个冗余元素。

修复方案

在配置项的options.plugins节点下新增legend配置,将display设为false关闭默认图例渲染即可。修改后的options配置片段如下:

options: {
    plugins: {
        // 关闭默认图例,移除冗余标签
        legend: {
            display: false
        },
        datalabels: {
            color: 'black'
        },
        title: {
            display: true,
            text: 'Marital Status'
        }
    }
}

替换原有配置后重新渲染图表,多余标签即可消失。


内容的提问来源于stack exchange,提问作者beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:57:16