Search code examples
rsubplotr-plotly

using ls() pattern to create list of plots for subplot


I am running a loop that assigns a plot to a variable. the code then pulls the variable names with the ls() pattern function

while (i > 0) {
assign(paste("fig", i, sep = ""), plot_ly(tot, y = ~gene, color = ~bx, type = "box", boxpoints = "all") %>% layout(annotations = list(x = 0 , y = 1, xanchor = "left",yanchor = "top",yshift = 20,showarrow = FALSE,font = list(size = 20), text = paste("Data", colnames(total)[i+1]))))
  i = i-1
  if (i == 0){

the code then pulls the variable names with the ls() pattern function and attempts to pass them as a list to subplot.

 ...
 l <- as.list(ls(pattern = "fig"))
    l <- do.call(paste, c(l,sep=", "))
    fig <- subplot(l,margin = 0.06,nrows=2) %>% layout(showlegend = FALSE)

 fig
 }
}'

This is where i am experiencing some errors.

  Error in [[: subscript out of bounds

Solution

  • Try the following :

    library(plotly)
    
    l <- mget(ls(pattern = "fig"))
    fig <- subplot(l,margin = 0.06,nrows=2) %>% layout(showlegend = FALSE)