R - 将对象存储在列表中

Xev*_*evi 4 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 
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,如果我查看列表的两个图,我得到了相同的结果,而如果我在没有 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
Run Code Online (Sandbox Code Playgroud)

我需要使情节数据静态...

谢谢!

西维

Kip*_*čys 6

添加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 
Run Code Online (Sandbox Code Playgroud)