1

ggplot2我已经创建了一个数字列表列,purrr现在我想用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 包(v0.2.0) 于 2018 年 3 月 12 日创建。

4

1 回答 1

4

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

cowplot::plot_grid(plotlist = plots$plot)
于 2018-03-12T18:50:02.417 回答