【问题标题】:How to show the percentage after the bar chart in react recharts?react recharts 如何在条形图后显示百分比?
【发布时间】:2022-12-01 07:25:45
【问题描述】:

我想在条形图之后显示这个百分比。我用 react recharts 做了这个

Check photo

         <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" />
          </BarChart>

【问题讨论】:

    标签: reactjs recharts


    【解决方案1】:

    您可以使用自定义工具提示编写自己的逻辑来显示百分比 如果你想看看工作示例 - https://codesandbox.io/s/epic-cache-kx8ze2?file=/src/App.js

     <BarChart
      width={500}
      height={300}
      data={data}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5
      }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip content={<CustomTooltip />} />
      <Legend />
      <Bar dataKey="amt" barSize={20} fill="#8884d8" />
    </BarChart>
    

    自定义工具提示

    const CustomTooltip = ({ active, payload, label }: any) => {
    
    
     if (active && payload && payload.length) {
        return (
          <div className="custom-tooltip">
            <p className="label">{`${label} : ${payload[0].value}`}</p>
        <p> percentage :  {percentage (payload)}</p>
          </div>
        );
      }
    
      return null;
    };
    

    计算百分比的函数

    const percentage = (data)=>{
      console.log(data[0].value);
          
          const total = 10000 
          const calcualtion = (data[0].value/total) * 100 // total to be replaced by the totla value
          return calcualtion
        
    
    }
    

    希望能帮助到你

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 2020-02-29
      • 2020-12-04
      • 1970-01-01
      • 2018-01-22
      • 2023-04-02
      • 2017-09-15
      • 2023-04-02
      相关资源
      最近更新 更多