Recharts - 条形图动态标签位置

use*_*234 5 reactjs recharts

如何获得如图所示的动态条形标签位置?

在此输入图像描述

这是我到目前为止的代码

const data = [
        { currency: 'CHF', amount: 3, amountLabel: 3023.00 },
        { currency: 'GBP', amount: 6, amountLabel: 6275.00 },
        { currency: 'USD', amount: 10, amountLabel: 9999.00 },
        { currency: 'EUR', amount: 14, amountLabel: 14819.00 },
        { currency: 'LEK', amount: 24, amountLabel: 24023000.00 },
    ];    
<BarChart
    width={430}
    height={170}
    data={data}
    layout="vertical">
    <XAxis type="number" orientation="top" stroke="#285A64" />
    <YAxis type="category" dataKey="currency" axisLine={false} dx={-5} tickLine={false} 
           style={{ fill: "#285A64" }} />
     <Bar background dataKey="amount" fill="#285A64" barSize={{ height: 26 }}>
        <LabelList dataKey="amountLabel" position="insideRight" style={{ fill: "white" }} />
     </Bar>
</BarChart>
Run Code Online (Sandbox Code Playgroud)

在这里找到示例代码jsfiddle

Dan*_*Dan 9

您应该实现一个要注入到 prop 中的 React 组件content(LabelList)

例如(JSFiddle):

const {BarChart, Bar, XAxis, YAxis, LabelList} = Recharts;
 const data = [
        { currency: 'CHF', amount: 3, amountLabel: 3023.00 },
        { currency: 'GBP', amount: 6, amountLabel: 6275.00 },
        { currency: 'USD', amount: 10, amountLabel: 9999.00 },
        { currency: 'EUR', amount: 14, amountLabel: 14819.00 },
        { currency: 'LEK', amount: 26, amountLabel: 26023000.00 },
    ];
    
const renderCustomizedLabel = (props) => {
  const {
    x, y, width, height, value,
  } = props;

const fireOffset = value.toString().length < 5;
const offset = fireOffset ? -40 : 5;
  return (
      <text x={x + width -offset} y={y + height - 5} fill={fireOffset ? "#285A64" :"#fff"} textAnchor="end">
        {value}
      </text>
  );
};

const VerticalBarChart = React.createClass({
    render () {
    return (
        <BarChart
                width={400}
                height={170}
                data={data}
                layout="vertical">
                <XAxis type="number" orientation="top" stroke="#285A64"/>
                <YAxis type="category" dataKey="currency" axisLine={false} dx={-10} tickLine={false} style={{ fill: "#285A64" }} />
                <Bar background dataKey="amount" fill="#285A64" barSize={{ height: 26 }}>
                    <LabelList dataKey="amountLabel" content={renderCustomizedLabel} position="insideRight" style={{ fill: "white" }} />
                </Bar>
            </BarChart>
    );
  }
})

ReactDOM.render(
  <VerticalBarChart />,
  document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)

  • 评论说这是一篇非常有用的帖子,我使用了这个解决方案!感谢你的分享! (2认同)