使用 ggplot 绘制多个图,每页 2 个

drawing multiple plots, 2 per page using ggplot

我有一个数据帧列表,我想将它们全部打印在一个 .RMarkdown 文档中,每页 2 个。但是,我一直无法找到这样做的来源。是否可以通过 for 循环执行此操作?

我想实现的是以下想法:


listOfDataframes <- list(df1, df2, df3, ..., dfn)

for(i in 1:){
   plot <- ggplot(listOfDataframes[i], aes(x = aData, y = bData)) + geom_point(color = "steelblue", shape = 19)

 #if two plots have been ploted break to a new page.

}

这可以用 rmarkdown 中的 ggplot 实现吗?我需要打印一份 PDF 文档。

如果您只需要每页输出两个图,那么我会按照上面的建议使用 gridExtra。如果您要将 ggplot 对象放入列表中,您可以这样做。

library(ggplot2)
library(shinipsum) # Just used to create random ggplot objects.
library(purrr)
library(gridExtra)

# Create some random ggplot objects.
ggplot_objects <- list(random_ggplot("line"), random_ggplot("line"))

# Create a list of names for the plots.
ggplot_objects_names <- c("This is Graph 1", "This is Graph 2")

# Use map2 to pass the ggplot objects and the list of names to the the plot titles, so that you can change them.
ggplot_objects_new <-
  purrr::map2(
    .x = ggplot_objects,
    .y = ggplot_objects_names,
    .f = function(x, y) {
      x + ggtitle(y)
    }
  )

# Arrange each ggplot object to be 2 per page. Use marrangeGrob so that you can save two ggplot objects per page.
ggplot_arranged <-
  gridExtra::marrangeGrob(ggplot_objects_new, nrow = 2, ncol = 1)

# Save as one pdf. Use scale here in order for the multi-plots to fit on each page.
ggsave("ggplot_arranged.pdf",
       ggplot_arranged, scale = 1.5)

如果您有要为其创建 ggplot 的数据框列表,则可以使用 purrr::map 来执行此操作。你可以这样做:

purrr::map(df_list, function(x) {
  ggplot(data = x, aes(x = aData, y = bData)) +
    geom_point(color = "steelblue", shape = 19)
})