首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Recharts -条形图动态标签位置

Recharts -条形图动态标签位置
EN

Stack Overflow用户
提问于 2020-04-24 16:10:54
回答 1查看 4K关注 0票数 1

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

这是我到现在为止的代码

代码语言:javascript
复制
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>

在这里找到示例代码jsfiddle

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-08 22:13:44

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

例如(JSFiddle):

代码语言:javascript
复制
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')
);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61403928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档