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

Xevi

我试图在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

塞浦路斯Kančys

添加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 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章