R中的图成单个pdf的列表

问题描述 投票:0回答:1

我正在尝试将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()

有人可以给我指导吗?我认为这不是代码本身的问题,而是我对代码正在发生的事情的理解。

r list pdf ggplot2 export
1个回答
0
投票

你很近。由于您的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:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.