多页 PDF 中以特定布局排列的绘图列表不起作用

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

假设在循环之外,我得到了一组特定的绘图,并将其保存在绘图列表中,就像我的可重现示例中一样。

plot_list = list()

for (i in 1:5){

dummy1 = ggplot(iris, aes(x = Petal.Length)) +
  geom_histogram()

dummy2 = ggplot(iris, aes(x = Petal.Length, color=Species)) +
  geom_boxplot()

dummy3 = ggplot(iris, aes(x = Petal.Length, y=Petal.Width, color=Species)) +
  geom_point()

plot_list[[length(plot_list)+1]] = list(dummy1,dummy2,dummy3) 

}

迭代之后,一旦我准备好绘图列表,我想创建一个 pdf 页面,并将特定的布局矩阵传递到每个页面。在不同的帖子之后我尝试过这段代码:

lay = rbind (c(1,1,2,2),
             c(1,1,3,3),
             c(1,1,3,3))


grDevices::cairo_pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(plot_list))) {
  do.call('marrangeGrob',list(plot_list[[i]], layout_matrix=lay))  
}
dev.off()

不幸的是,它只返回一个带有单页的空白 pdf。如有任何帮助,我们将不胜感激。

r ggplot2 gridextra
1个回答
0
投票

这是一种使用

lapply
而不是
for
循环和
patchwork
来组合绘图的方法:

library(patchwork)
library(ggplot2)

plot_list <- lapply(
  1:5,
  \(x) {
    list(
      ggplot(iris, aes(x = Petal.Length)) +
        geom_histogram(),
      ggplot(iris, aes(x = Petal.Length, color = Species)) +
        geom_boxplot(),
      ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
        geom_point()
    )
  }
)

lay <-
"
1122
1133
1133
"

grDevices::cairo_pdf("plots.pdf", onefile = TRUE)
lapply(
  plot_list, patchwork::wrap_plots,
  design = lay
)
#> [[1]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> 
#> [[2]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> 
#> [[3]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> 
#> [[4]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> 
#> [[5]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
dev.off()
#> quartz_off_screen 
#>                 2

第二个选择是使用

grid.arrange
:

grDevices::cairo_pdf("plots.pdf", onefile = TRUE)
for (i in seq(length(plot_list))) {
  grid.arrange(plot_list[[i]], layout_matrix = lay)
}
dev.off()
© www.soinside.com 2019 - 2024. All rights reserved.