I'm using Recharts for the first time in my React project I've positioned the legend of my BarChart component to the top right corner. However, I'm struggling to add spacing between the legend and the chart itself. Since the legend is positioned absolutely, I can't set any margin directly on it.
When attempting to change the legend's style to relative positioning, the legend gets displayed under the chart, ignoring the align and verticalAlign properties
Here's a snippet of my code:
<BarChart data={data}
barGap={8}>
<CartesianGrid strokeDasharray="3 3" vertical={false}/>
<XAxis tickFormatter={(index) => index + 1} tickMargin={16} tickLine={false}/>
<YAxis orientation={"right"} tickMargin={16} axisLine={false} tickLine={false}/>
<Tooltip content={<CustomTooltip/>}/>
<Legend
align="right" verticalAlign="top"
iconType="circle" iconSize={12}
formatter={(value, entry) => {
return <LegendText>{value} ({entry.payload.unit})</LegendText>
}}/>
<Bar name="Poids" unit="kg" dataKey="kilogram" fill="#282D30" barSize={7}
radius={[10, 10, 0, 0]}/>
<Bar name="Calories brûlées" unit="kCal" dataKey="calories" fill="#E60000" barSize={7}
radius={[10, 10, 0, 0]}/>
</BarChart>
How can I add a specific amount of spacing (e.g., 65px) between the legend and the chart in this setup?
Thank you!
Recharts is written using svg
s so most things have to be positioned absolutely. The legend wrapper however, is a div
Legend
has a wrapperStyle
prop which you can pass CSS to
<Legend
align="right"
verticalAlign="top"
iconType="circle"
iconSize={12}
wrapperStyle={{ paddingBottom: "20px" }}
/>