如何在 plotly js 中创建水平阈值线?

How to create a horizontal threshold line in plotly js?

我正在使用 plotly JS 创建一个简单的折线图。代码如下所示:

var trace1 = {
    x: [1, 2, 3, 4],
    y: [10, 15, 13, 17],
    type: 'scatter' 
};

var layout = {
    xaxis:{
    title:"X-Axis",
    tickangle:45,
    rangemode:'nonnegative',
    autorange:true,
    exponentformat: "none"
    },
    yaxis:{
    title: "Time",
    tickangle:45,
    rangemode:'nonnegative',
    autorange:false
    }
}
Plotly.newPlot(myDiv,[trace1],layout);

现在我想在图表上创建一条水平线,平行于我想横跨整个图表的 x 轴。为此,我在布局中添加了 'shapes',如下所示:

var layout = {
    xaxis:{
    title:"X_Axis",
    tickangle:45,
    rangemode:'nonnegative',
    autorange:true,
    exponentformat: "none"
    },
    yaxis:{
    title: "Time",
    tickangle:45,
    rangemode:'nonnegative',
    autorange:false
    },
    shapes: [
    {
        type: 'line',
        x0: 2,
        y0: 12.0,
        x1: 3,
        y1: 12.0,
        line:{
            color: 'rgb(255, 0, 0)',
            width: 4,
            dash:'dot'
        }
    }
    ]
};

添加 'shapes' 参数仅在我指定的 x 轴上的点 2 和点 3 之间创建一个水平值。

我的问题是如何在不依赖于 x 轴值的情况下使水平线跨越整个图表?任何帮助将不胜感激。

您可以将 xref 设置为 paper,这告诉 Plotly 不依赖于 x-axis 坐标,而是相对于整个图形的坐标,即 01.

var trace1 = {
    x: [1, 2, 3, 4],
    y: [10, 15, 13, 17],
    type: 'scatter' 
};

var layout = {
    shapes: [
    {
        type: 'line',
        xref: 'paper',
        x0: 0,
        y0: 12.0,
        x1: 1,
        y1: 12.0,
        line:{
            color: 'rgb(255, 0, 0)',
            width: 4,
            dash:'dot'
        }
    }
    ]
}
Plotly.newPlot(myDiv,[trace1],layout);
<script src="//cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>