如何在React Recharts的条形图后显示百分比?
实现Recharts垂直条形图后方显示百分比
要在你的垂直条形图(layout='vertical')的条形后方添加百分比,直接通过Recharts的Bar组件自带的label属性就能实现,步骤如下:
1. 先计算数据总和(用于百分比计算)
在组件里先算出所有pv字段的总和,这样才能得到每个条目占比:
const total = data.reduce((sum, item) => sum + item.pv, 0);
2. 修改Bar组件配置
给Bar添加label属性,指定位置为right(对应垂直条形图的条形后方),同时通过formatter函数生成百分比文本:
<BarChart width={window.innerWidth < 900 ? 280 : 380} height={200} data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5 }} layout='vertical' > {/* <CartesianGrid strokeDasharray="3 3" /> */} <XAxis type='number' tick={false} axisLine={false} /> <YAxis type='category' dataKey='name' width={window.innerWidth < 900 ? 110 : 120} stroke="#fff" style={{ fontSize: '14px' }} /> <Bar dataKey="pv" stackId="a" fill="#4EDCF0" label={{ position: 'right', // 百分比显示在条形右侧(后方) formatter: (value) => `${((value / total) * 100).toFixed(1)}%`, // 生成百分比,保留1位小数 style: { fill: '#fff', fontSize: '14px' } // 自定义文本样式 }} /> </BarChart>
补充说明
- 如果你的
data数组里已经预先计算好百分比字段(比如percent),可以直接在formatter里用entry.percent替代计算逻辑 - 可以调整
position的值(比如insideRight)来改变百分比的显示位置,根据需求选择即可
内容的提问来源于stack exchange,提问作者Faijul Azim
相关产品推荐
相关产品推荐

