在for循环中构建绘图图不会显示所有序列 [英] Building plotly graph in for loop not displaying all series

查看:89
本文介绍了在for循环中构建绘图图不会显示所有序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一次添加一列来创建图就可以了

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

但是,如果我尝试在for循环中执行相同的操作,它将仅显示第二条轨迹,并覆盖第一条轨迹.

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

有什么办法可以解决这个问题?我四处张望,设置"evaluate = TRUE"曾经是答案,但这似乎已被弃用.

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.

推荐答案

原因胜过我,但是您要问解决这个问题的任何方法".

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

您可以一次在循环中指定所需的y值,而不必一次传递整个data.table.

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

这篇关于在for循环中构建绘图图不会显示所有序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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