Grouping

Similarly, we can group histograms of a variable, just like we did with bar charts earlier. To do this, we use the facet_grid() function, which divides the plot to make the graphs easier to interpret. In facet_grid(), we simply specify in a formula (x ~ y) how the variable should be divided on the x-axis or y-axis. Here, we want to divide by gender on the y-axis.

histGroup <- ggplot(
  pss,
  aes(
    agea, 
    fill = gndr
  )
) +
  geom_histogram(
    aes(y = ..density..),
    alpha = 0.2
  ) + 
  geom_density(alpha = 0.2) +
  facet_grid(
    .~ gndr
  ) + 
  scale_fill_manual(
    name = "Gender", 
    labels = c(
      "Female", 
      "Male"
    ),
    values = beyonce_palette(72)
  ) +
  labs(
    x = "Age in years", 
    y = "Density", 
    title = "Histogram of Age"
  )

histGroup
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_bin()`).
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_density()`).

Adjustments

Next, we will modify the labels above the histograms and remove the legend (to avoid duplication!).

histGroup <- ggplot(
  pss,
  aes(
    agea, 
    fill = gndr
  )
) +
  geom_histogram(
    aes(y = ..density..),
    alpha = 0.2, 
    bins = 30, 
    position = "identity"
  ) + 
  geom_density(alpha = 0.2) +
  facet_grid(
    .~ gndr 
  ) + 
  scale_fill_manual(values = beyonce_palette(72)) +
  labs(
    x = "Age in years", 
    y = "Density", 
    title = "Histogram of Age"
  ) + 
  theme(legend.position = "none")

histGroup
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_bin()`).
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_density()`).

Alternatively, you can also create a Ridgeline plot. More on that on the next page!