首页 > 解决方案 > 在 Plotly 中使用循环制作形状

问题描述

到目前为止,我得到了这段代码`

shapes: [
    {
      type: "line",
      xref: "x",
      yref: "paper",
      x0: data[i],
      y0: 0,
      x1: data[i],
      y1: 1,
      line: {
        color: "red",
        width: 2,
        dash: "longdash",
      },
    },
  ],

我想在我的情节中的特定位置设置一条垂直线,这很好用。现在我怎样才能做更多完全相同的行?导致我的数据数组将在一个按钮后更新。如果我的数组中只有一个点,我会得到一条线,但如果尝试设置第二条线,它将无法正常工作。我可以以某种方式制作一个 for 循环来绘制这些线条吗?我只想在不同的地方绘制多个垂直车道。

标签: javascriptplotlyplotly.js

解决方案


您可以构造shapes为包含多个字典的数组:形式为[{shape 1 info}, ..., {shape N info}]. 为此,您可以遍历data数组,并将data[i]其用作数组中每一行的 x 坐标shapes

这是一些示例代码和codepen

var data = [1,2,3,5]
shapes = []
for (let i = 0; i < data.length; i++) {
  shapes.push({
      type: "line",
      xref: "x",
      yref: "paper",
      x0: data[i],
      y0: 0,
      x1: data[i],
      y1: 1,
      line: {
        color: "red",
        width: 2,
        dash: "longdash",
      },
   })
}

var trace1 = {
  x: [2, 6],
  y: [1, 2],
  mode: 'markers+lines'
};

var layout = {
  title: 'Vertical Line Annotations',
  xaxis: {
    range: [0, 7]
  },
  yaxis: {
    range: [0, 6]
  },
  shapes: shapes
};

var plotdata = [trace1];

Plotly.newPlot('myDiv', plotdata, layout);

在此处输入图像描述


推荐阅读