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

如何在ReChart中为堆叠条形图的每个条形设置不同颜色

解决Recharts堆叠条形图自定义类别颜色的问题

要实现每个类别(Skill/Role/Missions/Guild)的堆叠条用各自的颜色,不用单独渲染Bar组件,直接给Bar的fill属性传一个函数即可,这个函数会接收每个数据条目作为参数,返回对应条目的颜色字段值。

修改后的核心代码

把原来固定取data[0].color1的部分改成函数形式:

<Bar dataKey="After" stackId="a" fill={(entry) => entry.color1} />
<Bar dataKey="Before" stackId="a" fill={(entry) => entry.color} />

完整组件代码

import { BarChart, CartesianGrid, XAxis, YAxis, Tooltip, Bar } from "recharts";

const BarChartComponent = () => {
  const data = [
    {
      name: "Skill",
      Before: 4000,
      After: 2400,
      color1: "#53A9DA",
      color: "#BADDF0",
    },
    {
      name: "Role",
      Before: 3000,
      After: 1398,
      color1: "#DFD3F9",
      color: "#AF91F0",
    },
    {
      name: "Missions",
      Before: 2000,
      After: 9800,
      color1: "#FADCAF",
      color: "#F2A838",
    },
    {
      name: "Guild",
      Before: 2780,
      After: 3908,
      color1: "#CCEEB2",
      color: "#7FD33F",
    },
  ];
  return (
    <BarChart
      layout="vertical"
      width={600}
      height={400}
      data={data}
      margin={{
        top: 30,
        right: 5,
        bottom: 20,
        left: 50,
      }}
    >
      <CartesianGrid stroke="#f5f5f5" />
      <XAxis type="number" />
      <YAxis dataKey="name" type="category" />
      <Tooltip />

      <>
        <Bar dataKey="After" stackId="a" fill={(entry) => entry.color1} />
        <Bar dataKey="Before" stackId="a" fill={(entry) => entry.color} />
      </>
    </BarChart>
  );
};

export default BarChartComponent;

为什么这个方法可行

  • 函数形式的fill会遍历data数组里的每一项,针对每个类别返回对应的color1/color值,每个堆叠条的颜色都会匹配对应的数据项
  • 这种方式完全具备可扩展性,后续新增数据条目时,只要在数据里带上color和color1字段,组件不需要做任何修改就能自动应用新颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:01:20