【问题标题】:drawing multiple plots, 2 per page using ggplot使用 ggplot 绘制多个图,每页 2 个
【发布时间】:2021-07-09 15:26:48
【问题描述】:

我有一个数据框列表,我想将它们全部打印在 .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 文档。

【问题讨论】:

  • 只是为了澄清一下,您的输出 PDF 中是否只有绘图,或者您在 Markdown 文档中是否有其他信息?我已经看到了很多相关的问题,以帮助将绘图输出到 PDF(gridExtra::marrangeGrob() 可能值得探索),但在 Rmd 中没有那么多。
  • 好吧,我也看过一些例子,但我还没有看到实际代码,例如每页输出 2 个图。如果我只想在 Rmarkdown 中每页输出 2 个图,但我想更改每个图上的图标题,它将是怎样的代码。?谢谢
  • 所以你想在更大的 R 降价中绘制输出 PDF 而不是 sep PDF 的绘图?一些想法: 1. 将图组合成对,例如 patchworkcowplot,然后沿 these lines 插入分页符? (可能有一个更新的分页符选项?) 2. 将所有数据集与 ID 列堆叠在一起,并使用 ggforce::facet_wrap_paginate() a la this 循环,但在 Rmd 内而不是 pdf()

标签: r ggplot2 r-markdown pandoc


【解决方案1】:

如果您只需要输出每页两个的图,那么我会按照上面的建议使用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)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2020-10-18
    • 1970-01-01
    • 2021-12-19
    • 2021-10-11
    相关资源
    最近更新 更多