我正在关注折线图中的自定义点:https://recharts.org/en-US/examples/CustomizedDotLineChart
在我的图表中,我有 4 条线,对于每条线,我需要不同形状的数据点。
我点击了链接,它适用于链接中提供的 svg,但我需要圆形、三角形、矩形/正方形、菱形等形状
这是我的代码,
const CustomizedDot = (props) => {
const { cx, cy, dataKey } = props;
if (dataKey === 'A') {
return (
<svg >
<rect />
</svg>
);
}
if (dataKey === 'B') {
return (
<svg ">
<polygon points="0 40,40 80,80 40,40 0" />
</svg>
);
}
if (dataKey === 'C') {
return (
<svg >
<circle />
</svg>
);
}
if (dataKey === 'D') {
return (
<svg >
<polygon points="50 15, 100 100, 0 100"/>
</svg>
);
}
};
折线图是这样生成的
<LineChart
data={data.map((data) => ({
...data,
date: data.date,
}))}
>
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Legend />
{(Object.keys(lineConfig) as TimeSeriesMetricKey[]).reduce(
(items: React.ReactElement[], key) => {
return [
...items,
<Line
key={key}
dataKey={key}
name={lineConfig[key].legendLabel}
stroke={lineConfig[key].color}
strokeWidth={2}
activeDot={{r : 8}}
dot={<CustomizedDot />}
/>,
];
},
[]
)}
</LineChart>
我做错了一些事情,即形状不符合 SVG 中的条件,它显示所有线条都是圆形。
根据您提供的代码,您的
CustomizedDot
组件中可能存在一个小问题。您似乎忘记向 SVG
形状添加必要的属性,例如圆形的 cx
、cy
和 r
。以下是更新后的代码:
const CustomizedDot = (props) => {
const { cx, cy, dataKey } = props;
if (dataKey === 'A') {
return (
<svg>
<rect x={cx - 4} y={cy - 4} width={8} height={8} />
</svg>
);
}
if (dataKey === 'B') {
return (
<svg>
<polygon points={`${cx},${cy - 4} ${cx + 4},${cy + 4} ${cx - 4},${cy + 4}`} />
</svg>
);
}
if (dataKey === 'C') {
return (
<svg>
<circle cx={cx} cy={cy} r={4} />
</svg>
);
}
if (dataKey === 'D') {
return (
<svg>
<polygon points={`${cx - 2},${cy - 4} ${cx + 2},${cy - 4} ${cx},${cy + 4}`} />
</svg>
);
}
};
在这里,我们使用
cx
和 cy
属性根据数据点坐标正确定位形状,并为每个形状添加了适当的属性,如宽度、height
、r
和点使它们正确显示。
希望这有帮助!