是否可以在 Recharts 中在用户将鼠标悬停在 Y 位置处显示水平线并检索该 Y 值,以便我们可以将其显示在工具提示上?
https://meridian.a2z.com/components/tooltip/?platform=react-web
我一直在尝试做一些研究,研究如何获取鼠标悬停或单击的图表上的 Y 值,但我很难看出我们可以在哪里提取它。
有关我们可以用来获取这些数据的属性或组件的任何提示吗?我们甚至可以从图书馆访问它吗?
为了澄清这一点,我们试图获取用户将光标放在图表上的 Y 轴的值。
因此,如果图表看起来像这样,并且用户将鼠标放在粉红点位置,我将尝试获取 ~7000 的值 - 该图表位置的 y 值是多少
编辑:
关于响应性的注意事项: 如果您想使其具有响应性,只需根据应用于图表组件的填充/边距调整图表边界即可。
如果您正在尝试更高级的东西,并且需要将高度和宽度传递给图表组件以进行更多计算,那么以下文章应该会有所帮助:https://www.pluralsight.com/tech-blog/getting-size-and- React 中元素的位置/
注意:这有点破解,可能不是一个完美的解决方案,但它应该足以让您走上正轨
您应该能够使用onMouseMove 中的chartX 和chartY 字段。不幸的是,这只是光标下的像素值,但您应该能够将其转换为您用于图表的范围。
这是使用 SimpleLineChart 示例 recharts 组合在一起的示例。如果您只想获取用户光标下的 Y 值,并且还可以扩展以获取 X 值,那么这应该可行。
const {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
const data = [
{name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100},
];
//The pixel bounds for the LineChart, 0,0 is the top left corner
// these were found using the inspector built into the web browser
// these are in pixels but correspond to the values used in your graph
// so 246 is 0 Y on the graph and 5 is 10000 Y on the graph (according to your data)
const chartBoundsY = {min: 246, max: 5}
// The bounds we are using for the chart
const chartMinMaxY = {min: 0, max: 10000}
// Convert the pixel value from the cursor to the scale used in the chart
const remapRange = value => {
let fromAbs = value - chartBoundsY.min
let fromMaxAbs = chartBoundsY.max - chartBoundsY.min
let normal = fromAbs / fromMaxAbs
let toMaxAbs = chartMinMaxY.max - chartMinMaxY.min
let toAbs = toMaxAbs * normal
return Math.ceil(toAbs + chartMinMaxY.min)
}
const SimpleLineChart = React.createClass({
render () {
return (
<LineChart
width={600} height={300} data={data}
margin={{top: 5, right: 30, left: 20, bottom: 5}}
onMouseMove={props => {
// We get the values passed into the onMouseMove event
if(props.isTooltipActive) {
// If the tooltip is active then we display the Y value
// under the mouse using our custom mapping
console.log(remapRange(props.chartY))
}
}}
>
<XAxis dataKey="name"/>
<YAxis/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/>
<Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
)
}
})
ReactDOM.render(
<SimpleLineChart />,
document.getElementById('container')
)
Run Code Online (Sandbox Code Playgroud)
您可以在 jsfiddle 中打开此示例,然后将上面的代码粘贴到 JS 编辑器中来亲自尝试一下。http://recharts.org/en-US/examples
以下是 LineChart 鼠标事件的文档:http://recharts.org/en-US/api/LineChart