Grupar

Também podemos agrupar histogramas de uma variável por grupos, assim como fizemos com os gráficos de barras anteriormente. Para isso, usamos a função extra facet_grid(), que divide o gráfico para que as visualizações sejam mais claras. Em facet_grid(), simplesmente especificamos em uma fórmula (x ~ y) qual variável deve ser dividida no eixo x ou y. Agora queremos dividir apenas pelo sexo no eixo y.

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()`).

Ajustes

Agora vamos alterar as etiquetas sobre os histogramas e remover a legenda (para evitar duplicação!).

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()`).

Como alternativa, você também pode criar um Ridgeline Plot. Saiba mais na próxima página!