How to do custom x-axis ticks in a Recharts graph

Posted by Abbie Anker on Monday, May 20, 2024

I'd like to put more than one line in the x-axis ticks in a bar chart, something like this:

enter image description here

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:

enter image description here

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 https://recharts.org/en-US/examples/CustomizedLabelLineChart? 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.

1

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

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobm5sZWmAeX%2BOoaawZaSkeqW7jJysrKyfonq5ecCxoKxlpJ6wrL%2BMoqVmmV2nsqS0wKurrGWXp66xtA%3D%3D