R在循环内绘图添加轨迹 [英] R Plotly Add Trace within Loop

查看:74
本文介绍了R在循环内绘图添加轨迹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我不知道原因是什么,但在使用循环以曲线方式添加跟踪时遇到了一个问题.

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

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

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.

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

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

推荐答案

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

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

这篇关于R在循环内绘图添加轨迹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆