如何为Recharts环形图的innerRadius添加背景色并自定义Cell
给Recharts环形图内圈添加背景色并自定义Cell组件
你当前的环形图中间区域为空白,需要给innerRadius对应的内圈添加背景色,同时保留自定义Cell的样式。
解决方案
通过新增一个底层的背景Pie组件填充内圈空白,修改后的代码如下:
import { PieChart, Pie, Cell, Label } from 'recharts'; const data = [ { name: 'Completed', value: 67 }, { name: 'Approved', value: 10 }, // { name: 'Cancelled', value: 46 }, // { name: 'Pending', value: 67 }, ]; export default function Cancelled({ COLORS }) { return ( <div> <PieChart width={300} height={200}> {/* 内圈背景层 */} <Pie data={[{ value: 1 }]} cx="30%" cy="50%" dataKey="value" innerRadius={0} outerRadius={70} fill="#f0f0f0" // 可按需调整内圈背景色 /> {/* 原环形图层 */} <Pie data={data} cx="30%" cy="50%" dataKey="value" innerRadius={70} outerRadius={80} fill="#8884d8" > {data.map((entry, index) => { if (index === 1) { return <Cell key={`cell-${index}`} fill="#f3f6f9" />; } return <Cell key={`cell-${index}`} fill="green" />; })} <Label value={data[0].value} position="center" fill="black" style={{ fontSize: "32px", fontWeight: "normal", fontFamily: "Roboto", }} /> </Pie> </PieChart> </div> ); }
关键说明
- 新增的背景Pie组件使用单一数据项,渲染为完整圆形,刚好填充原环形图的内圈空白
- 背景Pie的
outerRadius与原Pie的innerRadius保持一致,innerRadius设为0,形成实心背景圆 - 背景Pie需放在原Pie组件之前,作为底层背景被环形图覆盖
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

