How to do custom x-axis ticks in a Recharts graph
Sophia Terry
I'd like to put more than one line in the x-axis ticks in a bar chart, something like this:
But all the props I have to control what renders there, underneath each group of bars, is the dataKey, so all I can get with Recharts is:
This is just rendering one value from my data.
Ideally I'd like to be able to pass XAxis a prop to render this such as:
<XAxis dataKey="name" render={(value, dataPoint) => ( <CustomXAxisName> <p>{value}</p> <p>{dataPoint.total} Principals</p> </CustomXAxisName>
)} />but I can find no affordances for this. There is a more flexible prop to configure label, but that refers to one label for the whole axis.
Is there anyway to get this? I'm quite surprised that I can't find a natural way to do this, since Rechart since so flexible in other regards and I don't think this is such a weird idea.
2 Answers
Have you looked at ? It shows how to put something diagonally in the x-axis, surely it can be used to put multiple lines.
It uses the tick={<CustomTick/>} prop to the XAxis component.
You can do it like:
const customizedGroupTick = (props: any) => { const { index, x, y, payload } = props; return ( <g> <g> <text x={x} y={y}> data </text> <text x={x} y={y }> data </text> </g> </g> ); };and then
<XAxis dataKey="Date" axisLine={false} tickLine={false} scale="band" tick={customizedGroupTick} interval={0} /> 1