如何在绘图中为形状添加名称或标签?

Abh*_*bhi 2 javascript plotly

我创建了一个简单的绘图折线图,如下所示:

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',
range:[0,20],
autorange: false
},
shapes: [
    {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold1,
    x1: 1,
    y1: threshold1,
    line:{
        color: 'rgb(255, 0, 0)',
        width: 2,
        dash:'dot'
        },
    },
    {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold2,
    x1: 1,
    y1: threshold2,
    line:{
        color: 'rgb(0, 255, 0)',
        width: 2,
        dash:'dot'
        },
    }
]
    };


Plotly.newPlot(myDiv,[trace1],layout);
Run Code Online (Sandbox Code Playgroud)

现在,我想为我在“布局”下的“形状”中创建的阈值 1 和阈值 2 添加名称或标签。我搜索了 plotly JS 文档,但没有得到任何有用的信息。我怎样才能做到这一点。任何帮助,将不胜感激。

Max*_*ers 7

您可以使用mode: 'text'. 这样做的方法肯定不止一种,但这种方法很简单,不需要复杂的数据复制。

var threshold1 = 12;
var threshold2 = 16;
var offset = 0.75;

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

var trace2 = {
  x: [Math.min.apply(Math, trace1.x) + offset, 
      Math.max.apply(Math, trace1.x) - offset],
  y: [threshold1 - offset, threshold2 - offset],
  mode: 'text',
  text: ['lower threshold', 'upper threshold'],
  showlegend: false
}

var layout = {
  xaxis: {
    title: "x-axis",
    tickangle: 45,
    rangemode: 'nonnegative',
    autorange: true,
    exponentformat: "none"
  },
  yaxis: {
    title: "Time",
    tickangle: 45,
    rangemode: 'nonnegative',
    range: [0, 20],
    autorange: false
  },
  shapes: [{
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold1,
    x1: 1,
    y1: threshold1,
    line: {
      color: 'rgb(255, 0, 0)',
      width: 2,
      dash: 'dot'
    },
  }, {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold2,
    x1: 1,
    y1: threshold2,
    line: {
      color: 'rgb(0, 255, 0)',
      width: 2,
      dash: 'dot'
    },
  }]
};


Plotly.newPlot(myDiv, [trace1, trace2], layout);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
Run Code Online (Sandbox Code Playgroud)