R - Plotly issue with multiple lines plotting simple loop

259 Views Asked by At

Hi using the code bellow I am not able to generate multiple lines, already tried other solutions as inherit, evauate = TRUE/FALSE and its not showing all the lines. If I use the same code outside the loop it works fine...

library("plotly")

test = data.frame(replicate(3,sample(0:10,10,rep=TRUE)))
test 

fig <- plot_ly()
for (i in names(test)){
  temp = test[[i]]
  print(temp)
  fig <- fig %>% add_trace(x = ~1:10, y = ~temp, type="scatter", mode = 'lines')
}
fig

output

1

There are 1 best solutions below

0
On BEST ANSWER

Try this. As you are adding the traces inside the loop without using a dataframe as argument, you could avoid the ~ symbol and invoke directly the values. Here the code:

library("plotly")

test = data.frame(replicate(3,sample(0:10,10,rep=TRUE)))
test 

fig <- plot_ly()
for (i in names(test)){
  temp = test[[i]]
  fig <- fig %>% add_trace(x = 1:10, y = temp, type="scatter", mode = 'lines')
}
fig

Output:

enter image description here