add multiple lines to a plot_ly graph with add_trace

痞子三分冷 提交于 2019-12-10 03:09:13

问题


I found an example to add lines to a plot_ly plot by using the add_trace command. How can I add a list of lines to plot without using add_trace multiple times?

I tried a for loop to add the traces but this doesn't work as expected.

my_lines <- list(
  list(x=1:10, y=2:11, color='red'),
  list(x=1:10, y=0:9, color='blue'),
  list(x=1:10, y=3:12, color='green')
)
p <- plot_ly()
p
for(line in my_lines) {  p <- add_trace(p, y=line[['y']], x=line[['x']], 
                 marker=list(color=line[['color']]))
}
p

But this for example works as expected.

p <- plot_ly()
p <- add_trace(p, y=my_lines[[1]][['y']], x=my_lines[[1]][['x']],
               marker=list(color=my_lines[[1]][['color']]))
p <- add_trace(p, y=my_lines[[2]][['y']], x=my_lines[[2]][['x']],
               marker=list(color=my_lines[[2]][['color']]))
p <- add_trace(p, y=my_lines[[3]][['y']], x=my_lines[[3]][['x']],
               marker=list(color=my_lines[[3]][['color']]))
p

Hope somebody can give me a hint on this.


回答1:


You need to set evaluate = TRUE to force evalutation / avoid lazy evaluation

p <- plot_ly()
p
for(line in my_lines) {  p <- add_trace(p, y=line[['y']], x=line[['x']], 
                 marker=list(color=line[['color']]),
                 evaluate = TRUE)
}
p



回答2:


I believe with the release of plotly 4.0 calling any of the add_* family of functions forces evaluation so there is no need to call evaluate = T anymore

So, something like this should work fine:

devtools::install_github("ropensci/plotly")
library(plotly)

p <- plot_ly()

for(i in 1:5){
  p <- add_trace(p, x = 1:10, y = rnorm(10), mode = "lines")
}

p



来源:https://stackoverflow.com/questions/38828875/add-multiple-lines-to-a-plot-ly-graph-with-add-trace

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