生成R个情节图的列表并将其传递给子图 [英] Generate list of R plotly plots and pass it to subplot
问题描述
通常在使用基本R图形(使用par(mfrow=c(nr,nc))
)时在for循环中生成子图.我试图通过生成一系列绘图并将它们保存到列表中以稍后传递给subplot
函数,来与plotly
做类似的事情.但是,由于我不明白的原因,在循环的结尾,列表的所有元素似乎都包含相同的图(最后一个图).如果我在循环内的列表中打印每个图(在下面的示例中取消注释以print
开头的行),则这些图看起来很好).我不太了解发生了什么.有人可以解释这种意外行为或在下面的示例代码中指出问题吗?
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)
推荐答案
尝试一下:
plotList[[thisName]] = plotly_build(plot_ly(x=x,y=y, name=thisName))
这篇关于生成R个情节图的列表并将其传递给子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!