I have two groups in my data, A1 and A2. Each group has about 50% men and an approximately normal distribution of age. I want to plot a histogram of age distribution in each group, by gender, and an overall age distribution by gender (and maybe a genderless one too?).
Is there a way to do this with facet_wrap? If not, is there a way I can manipulate my data (e.g. add a dummy variable) and add this?
Suppose you have:
library(tidyverse)
ggplot(iris,
aes(Sepal.Length, fill = Sepal.Width > 3)) +
geom_histogram() +
facet_wrap(~Species)
You could manipulate your data to include another copy of the dataset where Species is always "total." Then geom_histogram
will use the full dataset for the facet corresponding to "total."
ggplot(iris %>%
bind_rows(iris %>% mutate(Species = "total")),
aes(Sepal.Length, fill = Sepal.Width > 3)) +
geom_histogram() +
# I want 'total' at the end
facet_wrap(~fct_relevel(Species, "total", after = Inf), nrow = 1)