我有一个列表,p其中每个元素p都是ggplot2绘图对象的列表.
我想输出一个包含所有图表的pdf p,以便p[[1]]第1页上的图表,p[[2]]第2页上的图表等等.我怎么能这样做?
下面是一些示例代码,为您提供我正在使用的数据结构 - 为枯燥的图表道歉,我随机选择了变量.
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])
}
Run Code Online (Sandbox Code Playgroud)
Sve*_*ein 21
该解决方案与列表中列表的长度是否p不同无关.
library(gridExtra)
pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
do.call("grid.arrange", p[[i]])
}
dev.off()
Run Code Online (Sandbox Code Playgroud)
由于onefile = TRUE该功能pdf将所有图形按顺序保存在同一文件中(一个图形为一页).
chr*_*ris 12
这是Sven为R初学者提供的更简单版本的解决方案,否则他们会盲目地使用他们既不需要也不理解的do.call和嵌套列表.我有经验证据.:)
library(ggplot2)
library(gridExtra)
pdf("plots.pdf", onefile = TRUE)
cuts <- unique(diamonds$cut)
for(i in 1:length(cuts)){
dat <- subset(diamonds, cut==cuts[i])
top.plot <- ggplot(dat, aes(price,table)) + geom_point() +
opts(title=cuts[i])
bottom.plot <- ggplot(dat, aes(price,depth)) + geom_point() +
opts(title=cuts[i])
grid.arrange(top.plot, bottom.plot)
}
dev.off()
Run Code Online (Sandbox Code Playgroud)
这是使用ggplot2::ggsave()和将 ggplot 对象列表导出到单个 pdf 文件的最优雅的解决方案gridExtra::marrangeGrob()。
library(ggplot2)
library(gridExtra)
Run Code Online (Sandbox Code Playgroud)
假设您使用以下方法创建多个图 lapply()
p <- lapply(names(mtcars), function(x) {
ggplot(mtcars, aes_string(x)) +
geom_histogram()
})
Run Code Online (Sandbox Code Playgroud)
保存p地块列表:
ggsave(
filename = "plots.pdf",
plot = marrangeGrob(p, nrow=1, ncol=1),
width = 15, height = 9
)
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案,但我并不特别喜欢它:
ggsave("test.pdf", do.call("marrangeGrob", c(unlist(p,recursive=FALSE),nrow=2,ncol=1)))
问题在于它依赖于每组中有相同数量的地块。如果all(sapply(p, length) == 2)是假的,那么它将破裂。
小智 5
我已经尝试了其中一些解决方案,但没有成功。我进行了更多研究,并找到了一个非常适合我的解决方案。它将我的所有图形保存在一个 pdf 文件中,每个图表在一页上。
library(ggplot2)
pdf("allplots.pdf",onefile = TRUE)
for(i in glist){
tplot <- ggplot(df, aes(x = as.factor(class), y = value))
print(tplot)
}
dev.off()
Run Code Online (Sandbox Code Playgroud)