LeonaTheSun
LeonaTheSun

Reputation: 45

makes shapes with loop in Plotly

So far i got this code `

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

I want to set up a vertical line in my plot on a specific position and this works fine. Now how can i do more of the exact same line ? cause my array of data will be updated after a button. If there is only one point in my array i get a line , but if a try to set up a second line it just wont work. Can i somehow make a for loop to plot me those lines ? i just want to plot more than one vertical lane at different places.

Upvotes: 1

Views: 693

Answers (1)

Derek O
Derek O

Reputation: 19575

You can construct shapes as an array containing multiple dictionaries: something in the form [{shape 1 info}, ..., {shape N info}]. To do that you can loop through your data array, and use data[i] as the x-coordinates of each line in your shapes array.

Here is some sample code and the 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);

enter image description here

Upvotes: 1

Related Questions