0
votes

I want to make multiple plots for each level of a factor or each value of a numeric variable (here each value of vs variable). I do not want to use facet_grid or facet_wrap. I wonder if there is a more compact way to accomplish the task. In my actual data I do have many levels of a factor.

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()
2

2 Answers

1
votes

Maybe doing it like that?


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]]

1
votes

Use group_by, nest, purrr::pwalk to walk over the nested list of dataframes passing the grouping variable and the filtered dataframe to the custom function inside the pwalk call.

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)