在 Recharts 中,如何更改 y 轴刻度标签?

Sha*_*ron 3 reactjs recharts

我有以下图表:

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

在大多数情况下,这很好,并且 y 轴显示适当的刻度线范围。但是,对于一种特定类型的数据,我需要更改它。如果我有这种类型(由名为“itemType”的变量指示),那么所有数据值都将为 0 或 1;我希望 y 轴标签为“否”(而不是 0)和“是”(而不是 1)。

我认为我可以使用“tick”的自定义值来做到这一点,例如

 <YAxis interval="preserveStartEnd" domain={[0,domainMax]} tick={<CustomYAxisTick type={itemType} />} />
Run Code Online (Sandbox Code Playgroud)

在哪里

CustomYAxisTick是这样的:

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>);
  }
})
Run Code Online (Sandbox Code Playgroud)

但当我尝试这个时,它不起作用(我在 x 轴上有类似的东西,效果很好)。

有办法实现这一点吗?基本上,如果 itemType 为 BOOLEAN,则 y 轴刻度标签应为“No”和“Yes”;否则它应该只是从 0 到最大值的数字。

小智 5

我想你会想要使用tickFormatter属性: https: //recharts.org/en-US/api/YAxis#tickFormatter

你的 Y 轴应该是这样的:

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

其中formatYAxis是一个可能看起来像这样的函数(或多或少):

function formatYAxis(value) {
  if(value === 0) return "No"
  if(value === 1) return "Yes"
  return value
}
Run Code Online (Sandbox Code Playgroud)

您可能需要根据您的需求对此进行一些更改,但我认为这基本上就是您所需要的。请注意,“value”参数隐式传递给函数。