Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shade area between lines with ggplot2

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading