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
<- dplyr::filter(palmerpenguins::penguins, !is.na(sex))
peng_density ::glimpse(peng_density)
dplyr#> 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 providedata
Map the
flipper_length_mm
to thex
and addafter_stat(count)
Map
sex
tofill
Inside the
geom_density()
function, setposition
to"fill"
show/hide
<- labs(
labs_fill_density title = "Adult foraging penguins",
x = "Flipper length (mm)",
fill = "Sex")
<- ggplot(data = peng_density,
ggp2_fill_density aes(x = flipper_length_mm,
after_stat(count),
fill = sex)) +
geom_density(position = "fill")
+
ggp2_fill_density labs_fill_density
GRAPH: