R-将绘图对象存储在列表中

时间:2019-01-31 17:59:11

标签: r plotly

我正在尝试在for循环内生成不同的图并将其保存到列表中。问题在于,好像plotly的数据不是静态的,并且在每个循环中所有图都在变化。 这是我的代码:

library(plotly)
data("iris")
names = names(iris)[-5]

plotList <- list()
for (i in 1:length(names)) {
  for (j in 1:length(names)) {
    name = paste("plot", i, j, sep = "_")
    p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
                  type = "scatter", mode = "markers") %>%
            layout(
              title = paste(names[i], names[j], sep = " vs "),
              xaxis = list(title = names[i]),
              yaxis = list(title = names[j])))
    plotList[[name]] <- p
  }
}

plotList$plot_4_3
plotList$plot_4_4 

如您所见,如果我查看列表的两个图,我将得到相同的结果,而如果不执行for循环执行两个图,则将得到不同的结果,正确的结果:

i <- 4
j <- 3
p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
              type = "scatter", mode = "markers") %>%
        layout(
          title = paste(names[i], names[j], sep = " vs "),
          xaxis = list(title = names[i]),
          yaxis = list(title = names[j])))
p
i <- 4
j <- 4
p <- (plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
              type = "scatter", mode = "markers") %>%
        layout(
          title = paste(names[i], names[j], sep = " vs "),
          xaxis = list(title = names[i]),
          yaxis = list(title = names[j])))
p

我需要使绘图数据保持静态...

谢谢!

Xevi

1 个答案:

答案 0 :(得分:2)

添加plotly_build

library(plotly)
data("iris")
names = names(iris)[-5]

plotList <- list()
for (i in 1:length(names)) {
    for (j in 1:length(names)) {
        name = paste("plot", i, j, sep = "_")
        plotList[[name]] <- plotly_build(plot_ly(data = iris, x = ~get(names[i]), y = ~get(names[j]),
                      type = "scatter", mode = "markers") %>%
                  layout(
                      title = paste(names[i], names[j], sep = " vs "),
                      xaxis = list(title = names[i]),
                      yaxis = list(title = names[j])))
    }
}

plotList$plot_4_3
plotList$plot_4_4