'How to create in Recharts a custom vertical label for the YAxis that will scale to fit in case the label is too long?
I am building few composed charts using the Recharts library and some of the vertical labels on the YAxis
are too long and are getting cut off.
A picture of my labels that got cut off
I have tried to use a custom label with a <Text>
element - it solves the cutting off issue by making the label smaller if I pass a scaleToFit={true}
prop
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')
);
but the label doesn't rotate and remains horizontal.
This is a link to my fiddle reproducing the issue
How to solve this?
Solution 1:[1]
Found a solution - you should use the 'angle' prop in the element instead of the 'transform="rotate(x)".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dr.Boomerang |