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