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

如何配置ChartJS使数据标签显示labels文本而非数据集数值

解决方法

在你的options.plugins.datalabels配置中新增formatter回调,通过数据点索引读取对应label值返回即可,核心修改的配置块如下:

datalabels: {
    color: 'black',
    anchor: 'end',
    align: 'end',
    offset: 15,
    // 新增以下格式化逻辑
    formatter: (value, ctx) => {
        // 取当前数据项索引对应的labels文本返回
        return ctx.chart.data.labels[ctx.dataIndex];
    }
}

修改完成的完整代码如下:

<script>
var ctx = document.getElementById('myChart4').getContext('2d');
var myChart4 = new Chart(ctx, {
    plugins: [ChartDataLabels],
    type: 'doughnut',
    data: {
        labels: ['me','you','them'],
        datasets: [{
            label: false,
            data: [4,6,2],
        }]
    },
    options: {
        responsive: false,
        plugins: {
            datalabels: {
                color: 'black',
                anchor: 'end',
                align: 'end',
                offset: 15,
                formatter: (value, ctx) => ctx.chart.data.labels[ctx.dataIndex]
            },
            legend: {
                display: false
            },
            title: {
                display: true,
                text:'Reason'
            }
        },
        onClick: (evt, activeEls) => {
            show();
        },
    }
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:45:04