R中单个pdf的绘图列表

List of plot into single pdf in R

我正在尝试将 ggplot 项目列表导出到单个 .pdf 中。 我一直在 SO 中寻找提示,但找到的所有解决方案都不适合我。 我只能得到无法打开的带有 .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)

## create three example plots
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"


library(gridExtra)

pdf("plots.pdf", onefile = TRUE)
do.call("grid.arrange", p)  
dev.off()

生成的 .pdf: