R Plotly Add Trace within Loop

时光毁灭记忆、已成空白 提交于 2021-02-08 08:13:26

问题


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 P1


回答1:


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])
}


来源:https://stackoverflow.com/questions/54788327/r-plotly-add-trace-within-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!