
15 Stacked densities
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:

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 providedataMap the
flipper_length_mmto thexand addafter_stat(count)Map
sextofillInside the
geom_density()function, setpositionto"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_densityGRAPH:
