Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Recharts, how do I show just the first and final tick on an axis?

Tags:

recharts

I have a Recharts LineChart with 14 data points (although in future this may vary, so ideally I'd like to not have to hardcode that). I want to show 2 tick values on the XAxis - the first and last.

So, I have:

<LineChart width={100} height={50} data={lineData}>
  <Line type="monotone" dataKey="data" dot={false} />
  <XAxis />
</LineChart>

where lineData is:

"lineData": [
  { "data": 43.0 },
  { "data": 44.5 },
  { "data": 45.0 },
  { "data": 41.0 },
  { "data": 35.0 },
  { "data": 32.0 },
  { "data": 24.0 },
  { "data": 18.0 },
  { "data": 21.0 },
  { "data": 26.0 },
  { "data": 32.0 },
  { "data": 46.0 },
  { "data": 44.0 },
  { "data": 42.0 }
]

I've tried various combinations of interval, tickCount and a ticks array, but nothing has worked - eg the code above gives "1 3 6 9 13".

How do I show only the first and final ticks on the XAxis? They can be hardcoded, so let's say I want "12:00" at the start and "16:00" at the end. How do I achieve that?

like image 456
Sharon Avatar asked Sep 02 '25 06:09

Sharon


1 Answers

To show the first and last ticks on an axis, you can use the ticks props that takes an array with specific ticks to show. In this array, you could simply put the first, and last tick values.

If you need a specific label on the tick, you could add a property on the array, say name with the hard-coded name you wish to use, like this:

const lineData = [
  { "data": 43.0, "name": "12:00" },
  { "data": 44.5 },
  ...
  { "data": 44.0 },
  { "data": 42.0, "name": "16:00" }
];

And then, in the XAxis, specify the ticks to show:

<LineChart width={200} height={50} data={lineData}>
  <Line type="monotone" dataKey="data" dot={false} />
  <XAxis dataKey="name" ticks={['12:00', '16:00']} />
  <YAxis />
</LineChart>

Otherwise, if you do not wish a hard-coded label, you'll need to provide the 0 value and the lineData.length - 1 (13 in your example) value to set the first & last ticks.

Here is a fiddle to see the result with the hard-coded values: https://jsfiddle.net/hvgxw5pc/1/

like image 81
Orlyyn Avatar answered Sep 04 '25 20:09

Orlyyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!