我正在尝试将ggplot项目列表导出到单个.pdf中。我一直在这里寻找技巧,但是找到的所有解决方案都不适合我。我所能得到的都是无法打开的.pdf输出或没有页面的结果。
有人可以给我建议吗?
这是我的代码示例:
p <- lapply(x, fun)
#and i tried
library(gridExtra)
pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(p))) {
do.call("grid.arrange", p[[i]])
}
dev.off()
#and this
GG_save_pdf = function(list, filename) {
#start pdf
pdf(filename)
#loop
for (p in list) {
print(p)
}
#end pdf
dev.off()
invisible(NULL)
}
#and this too
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()
有人可以给我指导吗?我认为这不是代码本身的问题,而是我对代码正在发生的事情的理解。
你很近。由于您的p
是列表,因此do.call
足以将"grid.arrange"
应用于列表,无需循环等。
library(ggplot2)
library(gridExtra)
p <- replicate(3, ggplot(mtcars, aes(hp, mpg)) +
geom_point(), simplify=F)
str(p, 1)
# List of 3
# $ :List of 9
# ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
# $ :List of 9
# ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
# $ :List of 9
# ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
pdf("plots.pdf", onefile = TRUE)
do.call("grid.arrange", p)
dev.off()
结果.pdf: