r - 使用使用 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)
解决方案
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)
)
推荐阅读
- ios - 如何显示部分圆形微调器被阻止
- python-3.x - 我编写了一个用于识别闰年的 python 代码。它工作得很好,但代码似乎有点不对劲
- sqlite - 当我在数据库浏览器上查看我的数据库时,为什么我的外键没有显示?我输入错误了吗?
- python - 命令引发异常:AttributeError: 'str' object has no attribute 'id'
- r - 从一组数据框中重命名行名
- jquery - 如何使用 Jquery 和 SpringBoot 同时发布多个参数?
- docker - 在内部运行 docker 映像的程序,无需用户安装 docker
- c++ - 如何从 remade 函数计算数组的大小
- python - 在不同 PC 上对同一个句子使用 Spacy POS 时的时态差异
- javascript - 当我有气泡评论时,如何在 Here Maps 中使用“getContentElement()”参数?