r - 结合 purrr 和 cowplot 制作绘图网格

标签 r tidyverse purrr cowplot

我已经使用 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 创建于 2018-03-12 (v0.2.0).

最佳答案

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

cowplot::plot_grid(plotlist = plots$plot)

关于r - 结合 purrr 和 cowplot 制作绘图网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241141/

相关文章:

R h2o 从磁盘以 MOJO 或 POJO 格式加载保存的模型

r - 将文本粘贴到 dplyr mutate 中

r - 在 mutate 中添加变量标签

r - 相当于 purrr::map_df 中的 next

r - 如何在 purrr 中的多个数据集上拟合多个模型?

r - 创建多个根据现有变量计算的新变量

r - 将上面一行按下面一行划分

r - 在 attr() 中使用 mapply()

r - 按列减去数据帧的行,保留多因子列

r - 计算调查对象中某个值的百分比/频率