【发布时间】:2021-07-22 02:23:52
【问题描述】:
我有一个函数可以根据 mtcars 中“gear”的唯一值创建绘图列表
library(datasets)
library(magrittr)
library(ggplot2)
library(dplyr)
make_plots <- function(data) {
### create list of plot objects for every unique value of 'gear' (from mtcars)
p_list <- lapply(sort(unique(data$gear)), function(i) {
ggplot2::ggplot(data[data$gear == i,], ggplot2::aes(x = wt, y = mpg, color = factor(cyl))) +
ggplot2::geom_point() +
ggplot2::facet_wrap(~ gear) +
ggplot2::scale_color_discrete(name = "cyl")
})
p_list
}
### output list of plots
example_output <- make_plots(mtcars)
我想要什么: 基于“gear”唯一值的绘图列表,但根据每个“gear”值的关联“plot_type”具有不同类型的绘图输出,我将其创建为 mtcars 数据框中的另一列。所以地块数量相同,但地块类型不同。
### create new column of 'plot_type', where every unique gear value has the same 'plot_type', i.e.,
### all gears of 3 are of type 'scatter', all gears of 4 are of type 'bar', and all gear of 5 are of type
### 'log'
mtcars %>%
dplyr::mutate(plot_type = case_when(
gear == 3 ~ "scatter",
gear == 4 ~ "bar",
gear == 5 ~ "log"
))
我设想的大致如下所示,但显然遇到了麻烦。
make_plots <- function(data) {
### creates list of dataframes, with one dataframe per unique value of 'plot_type'
split_data <- data %>%
dplyr::group_split(plot_type)
p_type <- lapply(split_data[split_data$plot_type == i,], function(i) {
if(split_data[split_data$plot_type == "scatter"]) {
p_list <- lapply(sort(unique(split_data$gear)), function(i) {
ggplot2::ggplot(split_data[split_data$gear == i,], ggplot2::aes(x = wt, y = mpg, color = factor(cyl))) +
ggplot2::geom_point() +
ggplot2::facet_wrap(~ gear)
})
p_list
}
})
p_type
}
【问题讨论】: