15  Stacked densities

This graph is largely complete and just needs final proof reading.


This graph requires:

✅ a categorical variable

15.1 Description

Density graphs are typically used to visualize the distribution of a single variable, but stacked density graphs are great for visualizing how proportions vary across numeric (continuous) variables.

15.2 Set up

PACKAGES:

Install packages.

show/hide
install.packages("palmerpenguins")
library(palmerpenguins)
library(ggplot2)

DATA:

Artwork by Allison Horst

Remove missing sex from the penguins data.

show/hide
peng_density <- dplyr::filter(palmerpenguins::penguins, !is.na(sex))
dplyr::glimpse(peng_density)
#> Rows: 333
#> Columns: 8
#> $ species           <fct> Adelie, Adelie, Adelie…
#> $ island            <fct> Torgersen, Torgersen, …
#> $ bill_length_mm    <dbl> 39.1, 39.5, 40.3, 36.7…
#> $ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, 19.3…
#> $ flipper_length_mm <int> 181, 186, 195, 193, 19…
#> $ body_mass_g       <int> 3750, 3800, 3250, 3450…
#> $ sex               <fct> male, female, female, …
#> $ year              <int> 2007, 2007, 2007, 2007…

15.3 Grammar

CODE:

  • Create labels with labs()

  • Initialize the graph with ggplot() and provide data

  • Map the flipper_length_mm to the x and add after_stat(count)

  • Map sex to fill

  • Inside the geom_density() function, set position to "fill"

show/hide
labs_fill_density <- labs(
  title = "Adult foraging penguins",
  x = "Flipper length (mm)",
  fill = "Sex")
ggp2_fill_density <- ggplot(data = peng_density, 
       aes(x = flipper_length_mm, 
           after_stat(count),
          fill = sex)) +
      geom_density(position = "fill") 
ggp2_fill_density + 
  labs_fill_density

GRAPH: