结合 purrr 和 cowplot 制作绘图网格

combining purrr and cowplot to make a plot grid

我已经使用 purrr 创建了包含 ggplot2 个数字的列表列,现在我想使用 cowplot::plot_grid() 将它们组合成一个图。我怎样才能做到这一点?有一种蛮力方法可以做到这一点,但是当我不先验知道列表列中将有多少元素时,这可能行不通。

### libraries needed
library(tidyverse)
# install.packages("devtools")
devtools::install_github("IndrajeetPatil/ggstatsplot")

### creating list column with plots
plots <- datasets::mtcars %>%
  dplyr::mutate(.data = ., cyl2 = cyl) %>%
  dplyr::group_by(.data = ., cyl) %>%
  tidyr::nest(data = .) %>%
  dplyr::mutate(
    .data = .,
    plot = data %>%
      purrr::map(
        .x = .,
        .f = ~ ggstatsplot::ggbetweenstats(
          data = .,
          x = am,
          y = mpg,
          title = as.character(.$cyl2)
        )
      )
  )
#> Warning:  aesthetic `x` was not a factor; converting it to factorReference:  Welch's t-test is used as a default. (Delacre, Lakens, & Leys, International Review of Social Psychology, 2017).Note:  Bartlett's test for homogeneity of variances: p-value =  0.317Warning:  aesthetic `x` was not a factor; converting it to factorReference:  Welch's t-test is used as a default. (Delacre, Lakens, & Leys, International Review of Social Psychology, 2017).Note:  Bartlett's test for homogeneity of variances: p-value =  0.144Warning:  aesthetic `x` was not a factor; converting it to factorReference:  Welch's t-test is used as a default. (Delacre, Lakens, & Leys, International Review of Social Psychology, 2017).Note:  Bartlett's test for homogeneity of variances: p-value =  0.201

### creating a grid with cowplot

# brute force way to do this would be
# this works fine with 3 plots, but I might have way more plots than that
cowplot::plot_grid(plots$plot[[1]],
                   plots$plot[[2]],
                   plots$plot[[3]],
                   nrow = 3,
                   ncol = 1, 
                   labels = c("(a)","(b)","(c)"))

# searching for a more tidy and elegant way to do this
# my attempted code
cowplot::plot_grid(plotlist = list(plots$plot),
                     nrow = 3,
                     ncol = 1, 
                     labels = c("(a)","(b)","(c)"))
#> Error in plot_to_gtable(x): Argument needs to be of class "ggplot", "gtable", "grob", "recordedplot", or a function that plots to an R graphicsdevice when called, but is a list

reprex package (v0.2.0) 创建于 2018-03-12。

plots$plot 已经是一个地块列表,所以你需要做的就是调用

cowplot::plot_grid(plotlist = plots$plot)