如何在 Recharts 中为 YAxis 创建自定义垂直标签,该标签将缩放以适应标签太长的情况?

IT技术 javascript reactjs recharts
2021-05-27 02:09:46

我正在使用 Recharts 库构建一些组合图表,并且其中的一些垂直标签YAxis太长并且正在被切断。

我的标签被剪掉的照片

我尝试将自定义标签与<Text>元素一起使用- 如果我传递scaleToFit={true}props,它会通过使标签变小来解决切断问题

const {PropTypes} = React;
const {ComposedChart, Line, Area, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, Text} = Recharts;
const data = [{name: 'Page A', uv: 590, pv: 800, amt: 1400},
              {name: 'Page B', uv: 868, pv: 967, amt: 1506},
              {name: 'Page C', uv: 1397, pv: 1098, amt: 989},
              {name: 'Page D', uv: 1480, pv: 1200, amt: 1228},
              {name: 'Page E', uv: 1520, pv: 1108, amt: 1100},
              {name: 'Page F', uv: 1400, pv: 680, amt: 1700}];

const CustomizedLabelB = ({ kapi, metric, viewBox }) => {
    return (
        <Text
            x={0}
            y={0}
            dx={-300}
            dy={40}
            textAnchor="start"
            width={180}
            transform="rotate(-90)"
            // If I uncomment the next line, then the rotation stops working.
            // scaleToFit={true}
        >            
            This_is_a_very_very_very_long_long_long_label_what_can_we_do_about_it?
        </Text>
    );
};

const SameDataComposedChart = React.createClass({
    render () {
    return (
        <ComposedChart width={600} height={400} data={data}
            margin={{top: 20, right: 20, bottom: 20, left: 20}}>
          <CartesianGrid stroke='#f5f5f5'/>
          <XAxis dataKey="name"  />
          <YAxis label={<CustomizedLabelB />} />
          <Tooltip/>
          <Legend/>
          <Bar dataKey='uv' barSize={20} fill='#413ea0'/>
          <Line type='monotone' dataKey='uv' stroke='#ff7300'/>
       </ComposedChart>
    );
  }
})

ReactDOM.render(
  <SameDataComposedChart />,
  document.getElementById('container')
);

但标签不会旋转并保持水平。

这是我的小提琴重现问题的链接

如何解决这个问题?

1个回答

找到了一个解决方案 - 您应该在元素中使用 'angle' props而不是 'transform="rotate(x)"。