sam81
sam81

Reputation: 633

Generate list of R plotly plots and pass it to subplot

I usually generate subplots in a for loop when using base R graphics (using par(mfrow=c(nr,nc))). I'm trying to do something similar with plotly, by generating a series of plots and saving them to a list to be later passed to the subplot function. However, for reasons that I don't understand, at the end of the loop all the elements of the list seem to contain the same plot (the last one). If I print each plot in the list within the loop (uncommenting the line starting with print in the example below), then the plots seem fine). I don't really understand what's going on. Could someone explain this unexpected behavior or point out issues with my example code below?

library(plotly)
plotList = list()
plotListNames = c("p1", "p2", "p3")

for (i in 1:3){
    x = rnorm(10)
    y = rnorm(10)
    thisName = plotListNames[i]
    plotList[[thisName]] = plot_ly(x=x,y=y, name=thisName)
    ##print(plotList[[thisName]]
}

sbp = subplot(plotList[["p1"]], plotList[["p2"]], plotList[["p3"]])
print(sbp)

Upvotes: 4

Views: 3352

Answers (1)

Ayesha Kashif
Ayesha Kashif

Reputation: 41

try this:

plotList[[thisName]] =  plotly_build(plot_ly(x=x,y=y, name=thisName))

Upvotes: 4

Related Questions