首页 > 解决方案 > 使用使用 lapply 的函数后如何获得 ggplot grobs?

问题描述

我正在尝试使用 lapply 安排从函数生成的 grobs,但是尝试传递到 gList 的数据多于 grid 函数可以使用的数据,这里有一些可重现的代码:

library(dplyr)
library(gridExtra)

split_ex <- mtcars %>% split(cyl)
list_ex <- unique(mtcars$cyl)

test_plot <- function(dat){
subtest_plot <- function(type) {
  ggplot(data=dat %>% filter(cyl==type)) +
    geom_col(aes(y=mpg,x=disp)) +
    labs(title=type)
}
lapply(list_ex, function(type) subtest_plot(type))
}

grid.arrange(test_plot(mtcars),ncols=2)

标签: rggplot2r-grid

解决方案


library(dplyr)
library(grid)
library(ggplot2)
library(gridExtra)

split_ex <- mtcars %>% split(cyl)
list_ex <- unique(mtcars$cyl)

test_plot <- function(dat){
  subtest_plot <- function(type) {
    ggplot(data=dat %>% filter(cyl==type)) +
      geom_col(aes(y=mpg,x=disp)) +
      labs(title=type)
  }
  lapply(list_ex, function(type) subtest_plot(type))
}

grid.newpage()
grid.draw(
  arrangeGrob(grobs=test_plot(mtcars), ncol=2)
)

在此处输入图像描述


推荐阅读