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

Chart.js混合柱状图(Bar)与散点图(Scatter)时如何显示数值

解决Chart.js散点与柱状图显示数值的问题

问题核心

你的代码存在两处关键问题:

  • plugins配置位置错误,Chart.js的插件配置必须放在options对象内部,而非配置根节点
  • 散点图的data是包含x/y的对象,当前formatter直接返回value无法正确提取数值;同时未针对散点和柱状图的布局差异设置标签位置

解决方案

  1. 引入必要依赖:确保页面中已引入chartjs-plugin-datalabels插件(Chart.js本身不内置该数据标签功能)
  2. 修正配置结构:将datalabels插件配置移至options.plugins下
  3. 区分数据集处理数值:在formatter中判断数据集类型,散点图取value.y,柱状图直接返回数值
  4. 针对性设置标签位置:给散点图单独配置标签锚点和对齐方式,避免与柱状图布局冲突

修改后的完整代码

// setup
const data = {
    labels: ['A', 'B', 'C'],
    datasets: [{
        type: 'scatter',
        label: 'Count',
        data: [
            { x: 0, y: 30 },
            { x: 0, y: 50 },
            { x: 0, y: 40 }
        ],
        backgroundColor: 'blue',
        // 散点图单独配置数据标签位置
        datalabels: {
            anchor: 'right',
            align: 'center',
            color: '#333'
        }
    },
    {
        label: 'SumA',
        data: [50, 70, 60],
        backgroundColor: 'orange',
        border: 0
    },
    {
        label: 'SumB',
        data: [20, 40, 30],
        backgroundColor: 'yellow',
        border: 0
    },
    {
        label: 'SumC',
        data: [20, 40, 30],
        backgroundColor: 'green',
        border: 0
    }]
};

// config
const config1 = {
    type: 'bar',
    data,
    options: {
        scales: {
            x: { beginAtZero: true },
            y: { beginAtZero: true }
        },
        plugins: {
            datalabels: {
                // 柱状图默认标签配置
                anchor: 'end',
                align: 'top',
                color: '#333',
                formatter: function(value, context) {
                    // 根据数据集类型返回对应数值
                    return context.dataset.type === 'scatter' ? value.y : value;
                }
            }
        }
    }
};

// render init block
const mychart = new Chart(document.getElementById('myChart'), config1);

额外提示

如果需要散点对应到A/B/C不同分类,可将散点的x值改为0、1、2(分别对应数组中A、B、C的索引),就能让散点分布在对应分类上方。

内容的提问来源于stack exchange,提问作者Thanh Tùng Phạm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:43:18