【问题标题】:R - Storing plotly objects inside a listR - 在列表中存储情节对象
【发布时间】:2019-01-31 17:59:11
【问题描述】:

我正在尝试在 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

我需要将 plotly 数据设为静态...

谢谢!

西维

【问题讨论】:

    标签: r plotly


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2020-02-17
      相关资源
      最近更新 更多