首页 > 解决方案 > 试图在图表中创建一条垂直线

问题描述

所以我有一个用图表创建的图表,我想在其中创建一条垂直线,并在其中将其标记为红色。我尝试使用参考线,但它并没有真正起作用。我的代码看起来像这样:

const FEATURES = [{
    name: "y1",
    color: "orange"
},{
    name: "y2",
    color: "red"
},{
    name: "y3",
    color: "green"
},{
    name: "y4",
    color: "blue"
},{
    name: "y5",
    color: "pink"
},{
    name: "y6",
    color: "black"
}
]

const createLines = () => {
    let lines = []
    FEATURES.forEach((feature) => {
        lines.push(<Line strokeWidth={2} dot={false} animationDuration={500} isAnimationActive={true} animationEasing="linear" type="linear" yAxisId={feature.name} dataKey={feature.name} stroke={feature.color} />)
    })
    return lines
}

const createYAxis = () => {
    let yAxis = []
    FEATURES.forEach((feature, index) => {
        yAxis.push(<YAxis yAxisId={feature.name} orientation={(index % 2 == 0) ? "right" : "left"} tick={{ stroke: feature.color }} dataKey={feature.name}></YAxis>)
    })
    return yAxis
}

const AnalysisChart = (props) => {
{/*markupDate is the value in the x axis I want to make the line itself, more specifically 14.10.18 20:16:00*/}
    const markupDate = moment.utc(props.chosenAnalysisDateTime).format("DD.MM.YY HH:mm:SS")
    return (
        <div className="analysisShadowContainer">
            <div className="analysisContainer">
                <div className="header">
                    <span className="exit-button" onClick={() => props.setIsAnalysisOpen(false)}>X</span>
                </div>
                <LineChart width={1200} height={300} data={props.analysisData}>
                    {createLines()}
                    <CartesianGrid stroke="#ccc" />
                    <Tooltip />
                    <Legend verticalAlign="top" height={36} />
                    <XAxis alwaysShow={true} scale="auto" dataKey="datetime" tickFormatter={(datetime) => moment(datetime).format("DD.MM.YY HH:mm:SS")} />
                    <ReferenceLine strokeDasharray="3 3" yAxisId={"y6"} x={markupDate} stroke="red" label="Min PAGE" />
                    {createYAxis()}
                </LineChart>
            </div>
        </div>
    )
}

我在网上四处寻找一些解决方案,但找不到任何有用的东西。我尝试使用 ReferenceLine 的道具,遇到了一个问题,我“无法读取参考线中未定义的“比例””,添加了一个“yAxisId”道具,这是我在网上阅读的,但还没有真正成功使垂直线实际出现在图形中: 当前图形与我想要垂直线的位置

是否有另一种方法可以添加垂直线?

标签: reactjsrecharts

解决方案


ReferenceLine正是您在图表中需要在图表中显示垂直线的组件。

要设置 的xReferenceLine,文档声明道具x必须是数字或字符串。在您的代码中,您给出的结果moment.utc(...)不是它们中的任何一个。尝试将结果转换为字符串(如 markupDate.toString()),以获得更好的结果。


推荐阅读