繁体   English   中英

Recharts 在点之间单击

[英]Recharts click between points

我有一个由 N 个点组成的折线图(来自 Recharts,React),我想在特定的 X 处设置一个 ReferenceLine。

当我手动设置参考线的 X 值时,一切正常(例如,x={35}),而如果我单击折线图,参考线会自动绘制在最近的 X 处。

如何解决这个问题?

import { Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts";
import React from "react";
import {useState} from "react";


function App() {

    function handleClick(event) {
        //console.log(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}
                //x={35}
                stroke={"black"}
                strokeWidth={1}
                strokeDasharray="3 3"
            />
            
        </LineChart>
    );
}

export default App;

您可以按照此处文档中的说明从d3-scale package 传递自定义scale道具。

const scale = scaleLinear().domain([0, 100])

然后分配给您的 XAxis 组件:

<XAxis
  ...
  scale={scale}
  ticks={scale.ticks()}
/>

然后当有点击事件时,将chartX值转换为x轴刻度:

scale.invert(event.chartX)

来自Github的相关答案。

编辑 quirky-wood-ght21l

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM