I am trying to plot multiple lines, using R and plot_ly in combination with add_trace. If I use the following code,it works like expected:
df <- data.frame(x=c(1,2,3), y=c(2,4,5), y=c(4,1,3))
p <- plot_ly(mode="lines", type="scatter")
p <- add_trace(p, x=~df[,1], y=~df[,2])
p <- add_trace(p, x=~df[,1], y=~df[,3])
p
If I try to use a for-loop instead like this, it does not work:
df <- data.frame(x=c(1,2,3), y=c(2,4,5), y=c(4,1,3))
p <- plot_ly(mode="lines", type="scatter")
for(i in 1:2)
{
p <- add_trace(p, x=~df[,1], y=~df[,i])
}
p
which gives me only a singleline (actually the later one)
May anybody explain me please, what happens here and how to fix the 2nd version? Thanks