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

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

问题描述

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

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

我想输出一个包含 p 中所有图的单个 pdf,这样 p[[1]] 中的图在第 1 页,图在p[[2]] 在第 2 页,等等.我该怎么做?

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])
}

推荐答案

此解决方案与列表p中的列表长度是否不同无关.

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()

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

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天全站免登陆