[英]How to Display Ticks and Labels for Month Numbers for 4 years in the X-Axis using Recharts
我正在寻找一种方法来显示月份数字,如下所示,使用 Recharts 库的折线图:
如您所见,图表从每年的第一个月开始,x 轴为 4 年的总数据,并且月份每年递增 2。 每年都有一条参考线,较粗的笔划参考线是当前年份和月份,随后是未来月份,包括显示的下一年第一个月。
如何在 x 轴上显示刻度以及用参考线表示的每年的月份编号(折线图的开头不应有参考线)? 我是新来的反应和recharts所以请耐心等待。 以下是我目前在 recharts 组件中的代码,它仅将参考线的年份作为占位符考虑在内:
<ResponsiveContainer height="500px" width="99%" aspect={4}>
<LineChart
width={500}
height={300}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid
vertical={false}
opacity="0.4"
/>
<XAxis
dataKey="name"
tickSize={4}
/>
<YAxis
type="number"
domain={[0, 20000]}
/>
<Tooltip
content={CustomTooltip}
/>
{on1 &&
<Line type="monotone"
dataKey="cv"
stroke="#BE1710"
strokeWidth={2}
isAnimationActive={false}
dot={{r:0}}
/>
}
{on2 &&
<Line type="monotone"
dataKey="uv"
stroke="#22766F"
strokeWidth={2}
isAnimationActive={false}
dot={{r:0}}
/>
}
{on3 &&
<Line type="monotone"
dataKey="pv"
stroke="#0E65BC"
strokeWidth={2}
isAnimationActive={false}
dot={{r:0}}
/>
}
<ReferenceLine
x="2021"
stroke="black"
strokeWidth={1}
/>
<ReferenceLine x="2020" strokeWidth={0.5}/>
<ReferenceLine x="2019" strokeWidth={0.5}/>
<ReferenceLine x="2018" strokeWidth={0.5} />
</LineChart>
</ResponsiveContainer>
在我看来,您希望每 12 个月(或滴答声)有一个 ReferenceLine,而不是特定年份的 ReferenceLine。
假设您的数据数组每年每个月都有一个值,您可以这样拥有 LineChart:
export default function App() {
return (
<ResponsiveContainer height="500px" width="99%" aspect={4}>
<LineChart
width={1000}
height={500}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid vertical={false} opacity="0.4" />
<XAxis
dataKey="month"
domain={[0, "dataMax"]}
tickSize={4}
interval={1}
/>
<YAxis type="number" domain={[0, 20000]} />
<Line
type="monotone"
dataKey="cv"
stroke="#BE1710"
strokeWidth={2}
isAnimationActive={false}
dot={{ r: 0 }}
/>
<Line
type="monotone"
dataKey="uv"
stroke="#22766F"
strokeWidth={2}
isAnimationActive={false}
dot={{ r: 0 }}
/>
<Line
type="monotone"
dataKey="pv"
stroke="#0E65BC"
strokeWidth={2}
isAnimationActive={false}
dot={{ r: 0 }}
/>
<ReferenceLine x="0" strokeWidth={0.5} />
<ReferenceLine x="12" strokeWidth={0.5} />
<ReferenceLine x="24" stroke="black" strokeWidth={1} />
<ReferenceLine x="36" strokeWidth={0.5} />
</LineChart>
</ResponsiveContainer>
);
}
在这里, ReferenceLine x
的值是硬编码的,其中给定的值与一年中的第一个月 (1) 相关联。
我这样做是假设您的数据数组包含以下元素:
{
month: 9,
year: 2020,
uv: 3490,
pv: 4300,
cv: 2100
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.