How to selectively render only those labels that match a tick for a Line component? #3730
-
I have a LineChart with a lot of data points. I would like to label the points on the chart, but labeling every point ends up looking very messy since the labels overlap. So that got me thinking that it would be nice to only include the labels that matched a tick mark on the x-axis. I've been trying to figure out how to do this with a custom renderLabel function, but I can't figure out how to do this. I created a codesandbox with a demo example: https://codesandbox.io/s/blazing-feather-983zpx?file=/src/App.js Anyone have any suggestions on how to solve this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @johansigfrids! Since you are using an ordinal XAxis and would like to display label for every 10th ticks, the function renderLabel(props) {
const { x, y, stroke, value, index } = props;
// Somehow skip rendering labels when the data point does
// not match up to a tick mark on the x-axis?
if (!ticks.includes(index)) {
return null;
}
return (
<text x={x} y={y} dy={0} fill={stroke} fontSize={12} textAnchor="end">
{value.toFixed(2)}
</text>
);
} Here is the codesandbox forked from yours -> demo |
Beta Was this translation helpful? Give feedback.
Hi @johansigfrids!
Since you are using an ordinal XAxis and would like to display label for every 10th ticks, the
index
property from the props it what you need.For your customized label renderer, you can add an early return with index checking like:
And boom!
Here is the codesandbox forked from yours -> demo