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

如何修改Recharts饼图中的图例颜色?

解决Recharts饼图图例颜色不匹配问题

你的代码核心问题是错误地将Legend组件作为Pie的子元素,Recharts中Pie的子元素应该用Cell来设置扇区颜色,而Legend是独立组件,需要和Pie同级放在PieChart内。

修正步骤:

  1. 导入Cell组件(如果还没导入)
  2. 用Cell替代Pie内部的Legend,给每个扇区设置颜色
  3. 在PieChart中添加独立的Legend组件,自动关联颜色或手动配置

完整示例代码:

import { PieChart, Pie, Cell, Legend } from 'recharts';

const COLORS = ['#000', '#3095B4', '#E6E6E6'];

<PieChart width={730} height={300}>
  <Pie
    data={data}
    innerRadius="90%"
    outerRadius="100%"
    paddingAngle={0}
    dataKey="value"
    isAnimationActive={false}
    nameKey="name" // 对应data中用于图例显示的字段
  >
    {/* 用Cell设置每个饼图扇区的颜色 */}
    {data.map((entry, index) => (
      <Cell key={`cell-${index}`} fill={COLORS[index]} />
    ))}
  </Pie>
  {/* 独立的Legend组件,自动匹配Cell的颜色 */}
  <Legend />
</PieChart>

自定义图例样式(可选)

如果需要更精细的图例控制,可以手动配置Legend的payload参数:

<Legend 
  payload={data.map((entry, index) => ({
    value: entry.name, // 图例显示的文字
    type: 'circle', // 图例标记的形状
    color: COLORS[index] // 图例标记的颜色
  }))}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:20:25