Generate list of R plotly plots and pass it to subplot

こ雲淡風輕ζ 提交于 2019-12-06 10:29:34

问题


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)

回答1:


try this:

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


来源:https://stackoverflow.com/questions/38130366/generate-list-of-r-plotly-plots-and-pass-it-to-subplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!