4

I have an issue with using loops to add trace in plotly, though I have no idea what the cause is.

If I try to make a plot using the method for P below, only the data for last column (HORSE) is shown. Rabbit and Dog still show up, but both display values for Horse.

If, however, I use the P1 method the graph works perfectly. I would really like to be able to do this within a loop as the length of columns varies.

 df <- data.frame(AGE    = c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5),
                  YEAR   = c(2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017),
                  RABBIT = c(0,5,2,6,8,5,8,4,3,6,2,7,5,5,9,9,1,4,4,6,5,3,7,7,6,8,2,6,9,1,9,1,1,2,10,1,10,10,4,2,4,8,7,0,3,4,5,7),
                  DOG    = c(2,5,0,8,2,5,9,5,10,5,10,3,8,9,2,7,5,1,1,4,6,7,7,0,6,5,7,2,2,9,4,2,6,0,7,1,7,6,9,9,9,5,5,9,0,9,10,2),
                  HORSE  = c(7,1,9,10,6,6,5,1,4,5,0,3,0,3,2,4,3,6,1,9,6,4,3,1,7,8,4,1,8,6,5,9,2,0,5,5,6,1,1,7,4,9,5,0,8,1,5,7)
 )
 
 L <- c("RABBIT","DOG","HORSE")
 
 P <- plot_ly(data = df)
 for(i in 1:length(L)){
   P<-add_trace(P, y=~df[[L[i]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[i])
 }

 P1 <- plot_ly(data = df)
 P1 <- add_trace(P1, y=~df[[L[1]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[1])
 P1 <- add_trace(P1, y=~df[[L[2]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[2])
 P1 <- add_trace(P1, y=~df[[L[3]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[3])

P enter image description here P1 enter image description here

1 Answer 1

12

You can use this solution:

P <- plot_ly(data = df)
for(k in 1:length(L)) {
   dfk <- data.frame(y=df[[L[k]]], AGE=df$AGE, YEAR=df$YEAR)
   P <- add_trace(P, y=~y, x=~AGE, frame =~YEAR, data=dfk, 
                  type="scatter", mode="lines", name = L[k])
}
Sign up to request clarification or add additional context in comments.

2 Comments

Worked perfectly
How to set AutoPlay with loop in start the plot?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.