[英]tidyverse: Multiple plots for each level of a factor or each value of a numeric variable
我想為一個因子的每個水平或一個數字變量的每個值(此處為vs
變量的每個值)繪制多個圖。 我不想使用facet_grid
或facet_wrap
。 我想知道是否有更緊湊的方法來完成任務。 在我的實際數據中,我確實有很多因素。
library(tidyverse)
mtcars %>%
dplyr::filter(vs == 0) %>%
ggplot(mapping = aes(x = wt, y = mpg)) +
geom_point()
mtcars %>%
dplyr::filter(vs == 1) %>%
ggplot(mapping = aes(x = wt, y = mpg)) +
geom_point()
也許那樣做?
plot_list <- map(.x = unique(mtcars$vs), ~ mtcars %>%
dplyr::filter(vs == .x) %>%
ggplot(mapping = aes(x = wt, y = mpg)) +
geom_point() +
ggtitle(.x))
plot_list[[1]]
使用group_by
, nest
, purrr::pwalk
遍歷數據purrr::pwalk
的嵌套列表,將分組變量和過濾后的數據框傳遞到pwalk調用中的自定義函數。
plot_vs <- function(vs, data){
g1<-
data %>%
ggplot(mapping = aes(x = wt, y = mpg)) +
geom_point()+
ggtitle(!!vs)
print(g1)
}
mtcars %>%
group_by(vs) %>%
nest() %>%
purrr::pwalk(plot_vs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.