Home > Enterprise >  Shade area between lines with ggplot2
Shade area between lines with ggplot2

Time:07-22

I want to shade the area between the grouped lines. I've tried different approaches but I don't manage to do it.

df <- data.frame(year = rep(c(1950:1955), each = 2),
                 gender = factor(rep(c("male", "female"), times = 6)),
                 value = c(40526812, 37450509, 43027405,
                            40135682, 45801088, 43130369,
                            48579427, 46077640, 50948574,
                            48493786, 53052094, 50537984))

df |> 
  ggplot(aes(year, value, group = gender))  
  geom_line()

enter image description here

Thanks in advance!

CodePudding user response:

You could define the boundaries of the area by using a pivot_wider to create the ymax and ymin of the area in geom_ribbon so you don't need to subset per argument. So it will be easier to reproduce. Here an example:

df <- data.frame(year = rep(c(1950:1955), each = 2),
                 gender = factor(rep(c("male", "female"), times = 6)),
                 value = c(40526812, 37450509, 43027405,
                           40135682, 45801088, 43130369,
                           48579427, 46077640, 50948574,
                           48493786, 53052094, 50537984))

library(ggplot2)
library(dplyr)
library(tidyr)
area <- df %>%
  pivot_wider(names_from = gender, values_from = value) %>%
  mutate(
    ymax = pmax(male, female),
    ymin = pmin(male, female)
  )

ggplot(data = df, mapping = aes(year, y = value, group = gender))  
  geom_line()  
  geom_ribbon(data = area, mapping = aes(year, ymin = ymin, ymax = ymax), alpha = 0.4, inherit.aes = FALSE ) 

Created on 2022-07-22 by the enter image description here

  • Related