R在循环内绘图添加轨迹

时间:2019-02-20 14:10:37

标签: r loops plotly add trace

尽管我不知道原因是什么,但在使用循环以曲线方式添加跟踪方面存在问题。

如果我尝试使用下面的P方法绘制图表,则仅显示最后一列(HORSE)的数据。兔子和狗仍然显示,但是都显示马的值。

但是,如果我使用P1方法,则该图将完美运行。我真的很希望能够在循环内随着列长的变化而做到这一点。

 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 个答案:

答案 0 :(得分:1)

您可以使用以下解决方案:

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