Building plotly graph in for loop not displaying all series

戏子无情 提交于 2019-12-04 03:42:46

问题


Creating a plot by adding one column at a time works just fine

exPlot <- plot_ly(data.table(matrix(1:9,ncol = 3)))
theCols <- c("V2","V3")
exPlot <- exPlot %>% add_lines(x = ~V1, y = ~get(theCols[1]), type = "scatter",mode = "lines")
exPlot <- exPlot %>% add_lines(x = ~V1, y = ~get(theCols[2]), type = "scatter",mode = "lines")
exPlot

but if I try to do the same thing in a for loop, it only displays the second trace, overwriting the first one.

exPlot <- plot_ly(data.table(matrix(1:9,ncol = 3)))
theCols <- c("V2","V3")
for(i in 1:2){
  exPlot <- exPlot %>% add_lines(x = ~V1, y = ~get(theCols[i]), type = "scatter",mode = "lines")
}
exPlot

Any way to get around this? I looked around a bit, and setting "evaluate = TRUE" used to be the answer, but that seems to have been deprecated.


回答1:


The reason beats me but you are asking for 'any way to get around this'.

Instead of passing the whole data.table at once, you could specify the required y-values in the loop and it should work.

df <- data.table(matrix(1:9,ncol = 3))
exPlot <- plot_ly(df[[1]])
theCols <- c("V2","V3")
for(i in 1:2){
  exPlot <- add_lines(exPlot,
                      y = df[[theCols[i]]],
                      type = "scatter",
                      mode = "lines")
}
exPlot


来源:https://stackoverflow.com/questions/43237136/building-plotly-graph-in-for-loop-not-displaying-all-series

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