Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Recharts, how do I change the y-axis tick labels?

I have the following chart:

<ResponsiveContainer width="100%" height={300}>
  <LineChart data={displayData}>
    <XAxis
      dataKey="date"
    />
    <YAxis
      interval="preserveStartEnd"
      domain={[0, domainMax]}
    />
    <Line
      type="linear"
      dataKey={key}
    />
  </LineChart>
</ResponsiveContainer>

In most cases this is fine, and the y-axis shows an appropriate range of tick marks. However, for one particular type of data, I need to change it. If I have this type (indicated by a variable called 'itemType') then all data values will be either 0 or 1; I want the y-axis labels to be "No" (instead of 0) and "Yes" (instead of 1).

I assumed I could do this with a customized value for "tick", eg

 <YAxis interval="preserveStartEnd" domain={[0,domainMax]} tick={<CustomYAxisTick type={itemType} />} />

where

CustomYAxisTick is something like this:

const CustomYAxisTick= ({ x, y, payload, itemType }: any) => {
  if (itemType ==="BOOLEAN") {
    if(payload.value === 0) return <text>No</text>;
    if(payload.value === 1) return <text>Yes</text>;
    return null;
  }else {
    return (<text>{payload.value}</text>);
  }
})

but when I tried this it didn't work (I have something similar in place for the x-axis, which works fine).

Is there a way to achieve this? Basically, if the itemType is BOOLEAN, then the y-axis tick labels should be "No" and "Yes"; otherwise it should just be the numbers from 0 to whatever the maximum value is.

like image 963
Sharon Avatar asked Sep 13 '25 21:09

Sharon


1 Answers

I think you are going to want to use the tickFormatter property: https://recharts.org/en-US/api/YAxis#tickFormatter

your Y Axis should look something like this:

<YAxis interval="preserveStartEnd" domain={[0,domainMax]} tickFormatter={formatYAxis} />

where formatYAxis is a function that might look something like this (more or less):

function formatYAxis(value) {
  if(value === 0) return "No"
  if(value === 1) return "Yes"
  return value
}

You might need to change this a little bit based on your needs, but I think this is basically what you need. Note that the "value" argument is implicitly passed to the function.

like image 164
megakeegman Avatar answered Sep 15 '25 12:09

megakeegman