将多个ggplots打印成一个pdf,每页多个图 [英] Printing multiple ggplots into a single pdf, multiple plots per page

查看:649
本文介绍了将多个ggplots打印成一个pdf,每页多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 p ,其中 p 的每个元素都是ggplot2绘图对象的列表。



我想输出一个包含 p 中所有图的单个pdf,使得 p [[1]] 位于第1页, p [[2]] 中的图表位于第2页,等等。我可以这样做吗?

下面是一些示例代码,用于为您提供我正在使用的数据结构 - 为无聊情节道歉,我随机选择变量。

  require(ggplot2)
p < - list()

剪切< - 独特(钻石$ cut)
for(i in 1:length(cuts)){
p [[i]] < - list()
dat < - subset(diamonds,cut == cut [i])
p [[i]] [[1]] < - ggplot(dat,aes(price,table))+ geom_point()+
opts(title = cuts [ i))
p [[i]] [[2]] < - ggplot(dat,aes(price,depth))+ geom_point()+
opts(title = cuts [i])
}


解决方这个解决方案与列表 p 中列表的长度是否不同是不相关的。

  library(gridExtra)

pdf(plots.pdf,onefile = TRUE)
for(i in seq(length(p )){
do.call(grid.arrange,p [[i]])
}
dev.off()

由于 onefile = TRUE 函数 pdf 将所有图形按顺序保存在同一个文件中(一个图形为一页)。


I have a list, p, where each element of p is a list of ggplot2 plotting objects.

I would like to output a single pdf containing all the plots in p such that the plots in p[[1]] are on page 1, the plots in p[[2]] are on page 2, etc. How might I do this?

Here's some example code to provide you with the data structure I'm working with--apologies for the boring plots, I picked variables at random.

require(ggplot2)
p <- list()

cuts <- unique(diamonds$cut)
for(i in 1:length(cuts)){
    p[[i]] <- list()
    dat <- subset(diamonds, cut==cuts[i])
    p[[i]][[1]] <- ggplot(dat, aes(price,table)) + geom_point() + 
        opts(title=cuts[i])
    p[[i]][[2]] <- ggplot(dat, aes(price,depth)) + geom_point() + 
        opts(title=cuts[i])
}

解决方案

This solution is independent of whether the lengths of the lists in the list p are different.

library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
  do.call("grid.arrange", p[[i]])  
}
dev.off()

Because of onefile = TRUE the function pdf saves all graphics appearing sequentially in the same file (one page for one graphic).

这篇关于将多个ggplots打印成一个pdf,每页多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆