Xevi
Xevi

Reputation: 399

R - Storing plotly objects inside a list

I’m trying to generate different plots inside a for loop and save them into a list. The problem is that it’s like the data of plotly isn’t static and in every loop all plots are changing. Here is my code:

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 

As you can see if I look at two plots of the list I get the same result, while if I execute the two plots without the for loop I get different results, the correct results:

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

I would need to make the plotly data static...

Thanks!

Xevi

Upvotes: 6

Views: 1743

Answers (1)

Kipras Kančys
Kipras Kančys

Reputation: 1779

Add 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 

Upvotes: 9

Related Questions