Graph info

Should I use this graph?


This graph requires:

✅ a categorical variable

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.

Getting set up

PACKAGES:

Install packages.

Code
install.packages("palmerpenguins")
library(palmerpenguins)
library(ggplot2)

DATA:

Artwork by @allison_horst

Remove missing sex from the penguins data

Code
peng_density <- filter(palmerpenguins::penguins, !is.na(sex))
glimpse(peng_density)
Rows: 333
Columns: 8
$ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
$ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
$ bill_length_mm    <dbl> 39.1, 39.5, 40.3, 36.7, 39.3, 38.9, 39.2, 41.1, 38.6…
$ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, 19.3, 20.6, 17.8, 19.6, 17.6, 21.2…
$ flipper_length_mm <int> 181, 186, 195, 193, 190, 181, 195, 182, 191, 198, 18…
$ body_mass_g       <int> 3750, 3800, 3250, 3450, 3650, 3625, 4675, 3200, 3800…
$ sex               <fct> male, female, female, female, male, female, male, fe…
$ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…

The 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"

Code
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: