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

Chart.js无需点击如何获取特定柱状条的yLabel以设置背景色

Chart.js 按数值动态设置柱状条背景色方法

你可以通过给 backgroundColor 传入回调函数的方式,拿到当前柱状条的上下文信息,获取所需的数值/标签做判断,具体实现如下:

核心逻辑

backgroundColor 支持接收回调函数,入参为当前柱状条的渲染上下文 context,你可以从上下文里直接拿到需要的字段:

  • 若你需要判断的是当前柱状条对应的y轴数值:取 context.parsed.y
  • 若你需要判断的是当前柱状条对应的x轴标签(也就是你代码里 labels 数组里的内容,比如Label 1、Label 2):取 context.label

修正后的示例代码

const testValue = 30; // 你的对比基准值
const waterFChart = new Chart(canvasRef.current, {
    plugins: [ChartDataLabels],
    type: "bar",
    data: {
        labels: ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"],
        datasets: [
            {
                label: 'Failures',
                type: "bar",
                data: [10, 20, 30, 41, 51],
                // 回调函数动态返回背景色
                backgroundColor: (context) => {
                    // 示例:判断y轴数值等于testValue则为红色,否则黄色
                    const currentValue = context.parsed.y;
                    return currentValue === testValue ? "red" : "yellow";
                    // 如果要判断x轴标签则改为:
                    // const currentLabel = context.label;
                    // return currentLabel === testValue ? "red" : "yellow";
                },
                hoverBackgroundColor: darkBar,
                stack: 'Stack 1',
            }
        ]
    }
});

额外说明

如果你的图表是横向柱状图,y轴放的是分类标签,x轴放的是数值,那么对应数值的字段改为 context.parsed.x 即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:27:03