r - 将在 for 循环中创建的多个 ggplots 保存到单个图

标签 r for-loop ggplot2 python-imaging-library

关闭。这个问题需要debugging details .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




我想在一个图中有多个 ggplots 图。
问题:尝试使用 for 循环创建绘图列表(稍后在 grid.arrange 中使用)时,该列表返回空。
我使用了这两个帖子:

1) create figures in a loop
2) use grid.arrange to save in a single fig

想出以下代码(更简单的版本)* 来绘制概率密度曲线:

#models = 33 obs of 1 variable
plotlist = list()
for (i in 1:33)
{
 modname = models$col1[i]
 p<- ggplot() + geom_line(aes(xi,yi)) + geom_line(aes(ai,bi)) + 
     ggtitle(modname) ## the x,y,a,b are just illustrative.
 #In reality, each pair is produced using fitdist and dgamma functions for
  # data (single column) from separate .csv
 ggsave(outpath)
 plotlist[[i]] = p   

}
main <- grid.arrange(grobs=plotlist,ncol=6)
main
ggsave("bigplot.png",p)

问题(进一步解释):plotlist显示为空列表。因此, grid.arrange 只绘制了在最后一个循环中创建的子图 33 次。但是,奇怪的是 grid.arrange 图为所有子图都有正确的标题(使用 modname 分配)!!!在附图中,您将看到除标题外所有子图都相同。由于我也保存了单个子图,因此我知道问题不在于子图的数据/代码。
main
我对 R 相当陌生,这是我的第一个 ggplot2(* 原谅多个 geom_line())。结果,我花了一段时间才弄清楚如何拟合分布并绘制它们(谢谢,stackoverflow !!)。因此,这里的任何帮助将不胜感激。

更新:我能够使用 完成上述操作PIL python中的包 .但是,我真的很希望能够在 R 中做到这一点。

最佳答案

如果我对你的理解正确(我不确定),这只是关于保存你的绘图文件。

我认为问题很简单,grid.arrange()不适用于 last_plot() ,这是什么ggsave显然使用。所以最好明确说明你希望它保存什么情节。

这是一个简单的工作示例,图较少,没有回归模型,只有一些随机图:

library(ggplot2)
library(gridExtra)
plotlist = list()
n <- 100
for (i in 1:9)
{
  df <- data.frame(x=rnorm(n),y=rnorm(n))
  pname <- paste0("Plot-",i)
  p<- ggplot(df) + geom_point(aes(x,y)) + ggtitle(pname)
  ggsave(paste0(pname,".png"),p)
  plotlist[[i]] = p   
}
p <- grid.arrange(grobs=plotlist,ncol=6)
ggsave("bigplot.png",p)

文本输出:

Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
Saving 4.76 x 5.28 in image
> p <- grid.arrange(grobs=plotlist,ncol=3)
> ggsave("bigplot.png",p)
Saving 4.76 x 5.28 in image


最后的情节:

enter image description here

关于r - 将在 for 循环中创建的多个 ggplots 保存到单个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43216262/

相关文章:

python - 弹出负数可以,但不能用于零

r - ggplot2 - 每组的叠加平均值

r - 针对困惑的数据进行旋转

r - 需要具有开始停止索引的更快的滚动应用功能

windows - 为什么不能在batch for循环中使用问号?

for-loop - Liquid - if contains 语句在 for 循环中不起作用

r - 在 ggplot 中注释分组箱线图 - 在箱线图下方添加观察数量

r - 有一组点线图和垂直线图的单独图例

r - 平滑样条(): fitted model does not match user-specified degree of freedom

r - 更改 R 中字符列的级别