rggplot2ggh4x

How to add shaded area to line plot with the ggh4x package?


I'm wanting to use stat_difference() from the ggh4x package to add a shaded area between two lines in my plot. I have melted my example dataset below as I thought this was the correct approach to facet_wrap all the variables in my dataset, but I'm unsure how to use stat_difference() with the categorical variable team. I essentially want the line corresponding to Team A or Team B shaded depending on which one has a higher value, similar to the example here. Any suggestions will be great! Thanks.

library(tidyverse)
library(ggh4x)
library(reshape2)

set.seed(100)
team <- rep(rep(paste("Team", LETTERS[1:2]), each = 20))
week <- rep(c(1:20), times = 2)

var_1 <- rnorm(n = 40, mean = 20, sd = 5)
var_2 <- rnorm(n = 40, mean = 20, sd = 5)
var_3 <- rnorm(n = 40, mean = 250, sd = 50)
var_4 <- rnorm(n = 40, mean = 100, sd = 50)

dat <- data.frame(team, week, var_1, var_2, var_3, var_4)

plot_dat <- melt(dat, id.vars = c("team", "week"))

ggplot(plot_dat, aes(x = week)) +
  geom_line(aes(y = value, color = team)) +
  facet_wrap(~variable, scales = "free_y")

Solution

  • Following the post you referenced you could achieve your desired result by making separate columns with the values for each team using e.g. pivot_wider, add the lines via two geom_line and then apply stat_difference:

    library(tidyverse)
    library(ggh4x)
    library(reshape2)
    
    plot_dat <- pivot_wider(plot_dat, names_from = team, values_from = value)
    
    ggplot(plot_dat, aes(x = week)) +
      geom_line(aes(y = `Team A`, color = "Team A")) +
      geom_line(aes(y = `Team B`, color = "Team B")) +
      facet_wrap(~variable, scales = "free_y") +
      stat_difference(aes(ymin =  `Team B`, ymax = `Team A`), alpha = 0.3)