Recharts折线图点击后ReferenceLine定位偏差问题求解
Recharts折线图点击时ReferenceLine自动定位到最近数据点的解决方法
我使用Recharts在React中创建了一个包含N个数据点的折线图,希望在指定X轴位置设置ReferenceLine。手动设置X值(如x={35})时一切正常,但点击折线图时,ReferenceLine会自动定位到最近的X轴数据点,请问该如何解决此问题?
原代码:
import { Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts"; import React from "react"; import { useState } from "react"; function App() { function handleClick(event) { setLine(event.activeLabel) } const data = [ { tag: 0, value: 10 }, { tag: 10, value: 10 }, { tag: 20, value: 30 }, { tag: 50, value: 20 }, { tag: 100, value: 10 } ]; const [line, setLine] = useState(); return ( <LineChart data={data} onClick={(event) => handleClick(event)} width={500} height={300} > <XAxis dataKey="tag" scale="linear" tick={true} type="number" domain={[0, 100]} /> <YAxis /> <Line type="monotone" dataKey="value" stroke="black" strokeWidth={3} dot={true} /> <ReferenceLine x={line} stroke="black" strokeWidth={1} strokeDasharray="3 3" /> </LineChart> ); } export default App;
问题原因
event.activeLabel返回的是离点击位置最近的数据点的tag值,而非点击位置对应的真实X轴坐标,所以ReferenceLine会自动跳到离散的数据点上。
解决方法
通过图表的坐标系转换,将点击的像素坐标转换为连续的X轴数值:
- 给LineChart添加ref以获取图表实例
- 在点击事件中,利用X轴的scale方法将像素坐标反转成对应的X轴数值
修改后的代码:
import { Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts"; import React, { useState, useRef } from "react"; function App() { const chartRef = useRef(null); const [line, setLine] = useState(); function handleClick(event) { if (!chartRef.current) return; // 获取X轴实例 const xAxis = chartRef.current.getXAxis(); if (!xAxis) return; // 将点击的像素横坐标转换为X轴数值 const xValue = xAxis.scale.invert(event.x); setLine(xValue); } const data = [ { tag: 0, value: 10 }, { tag: 10, value: 10 }, { tag: 20, value: 30 }, { tag: 50, value: 20 }, { tag: 100, value: 10 } ]; return ( <LineChart ref={chartRef} data={data} onClick={(event) => handleClick(event)} width={500} height={300} > <XAxis dataKey="tag" scale="linear" tick={true} type="number" domain={[0, 100]} /> <YAxis /> <Line type="monotone" dataKey="value" stroke="black" strokeWidth={3} dot={true} /> <ReferenceLine x={line} stroke="black" strokeWidth={1} strokeDasharray="3 3" /> </LineChart> ); } export default App;
关键说明
chartRef.current.getXAxis()获取当前图表的X轴实例xAxis.scale.invert(event.x)将点击位置的像素坐标(event.x)转换为对应的X轴连续数值,这样ReferenceLine就会精准定位到点击的位置,而不是最近的数据点
内容的提问来源于stack exchange,提问作者LauGroupie95
相关产品推荐
相关产品推荐

