Oh No
Oh No

Reputation: 165

Dynamically selected variables in plotly do not render correctly when saved in list but work

please see the toy example below that reproduces the error.

The print statement inside the loop works as expected and 3 different charts are produced.

However when "lst" is run after the loop, I expected the same 3 different charts to be rendered but I just get 3 copies of the same (third) chart.

("get()" works when using the the dynamically selected plot directly but putting it in the list, messes it up.)

library(plotly)

lst <- list()
cnt <- 1
for(bar in c("Sepal.Width", "Petal.Length", "Petal.Width")){
  lst[[cnt]] <- plot_ly(data = iris,
                        x = ~Sepal.Length,
                        y = ~get(bar),
                        type = "scatter",
                        mode = "markers")
  print(lst[[cnt]] %>% layout(title = paste(bar, "printed in loop")))
  cnt <- cnt + 1
}
lst

Changing "~get(bar)" to the below solves it. I would be grateful for an explanation.

y = as.formula(paste0("~", bar))

Upvotes: 1

Views: 261

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33510

You need to render the plotly objects before passing it to your list using plotly_build():

library(plotly)

lst <- list()
for(bar in c("Sepal.Width", "Petal.Length", "Petal.Width")){
  lst[[bar]] <- plot_ly(data = iris,
                        x = ~Sepal.Length,
                        y = ~get(bar),
                        type = "scatter",
                        mode = "markers") %>% plotly_build()
  print(lst[[bar]] %>% layout(title = paste(bar, "printed in loop")))
}

lst$Sepal.Width
lst$Petal.Length
lst$Petal.Width

Upvotes: 2

Related Questions