Home > Mobile >  grouped dataframe - groupings as facets in a ggplot?
grouped dataframe - groupings as facets in a ggplot?

Time:09-25

Some data

grp_diamonds <- diamonds %>% 
  group_by(cut) %>%
  group_split


grp_diamonds[[1]] %>% 
  ggplot(aes(x = carat, y = price))  
  geom_point()

This returns a plot for grp_diamonds[[1]] enter image description here

But grp_diamonds is actually a list of 5 dataframes since I used group_split() earlier.

Is there a clever way to automatically use the groups as facets?

Yes, in this example you could just do this:

diamonds %>% 
  ggplot(aes(x = carat, y = price))  
  geom_point()  
  facet_wrap(vars(cut))

But I wondered if there was a way to automatically facet based on existing groupings?

CodePudding user response:

Making use of dplyr::groups and dplyr::vars and !!!one option would be:

library(dplyr)
library(ggplot2)

grp_diamonds <- diamonds %>% 
  group_by(cut, color)

grp_diamonds %>% 
  ggplot(aes(x = carat, y = price))  
  geom_point()  
  facet_wrap(facets = vars(!!!groups(grp_diamonds)))

  • Related