1

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")
Ben_89
  • 249
  • 1
  • 8

1 Answers1

1

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)

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Yes this is the way to do it. Makes me think whether it is worth it to wrap line colouring functionality in a `geom_difference()` of some sort. – teunbrand Jan 29 '22 at 16:59
  • @teunbrand. Hm. May be worthwhile the effort. At least I wasn't aware that your package offers this "hidden gem". Up to now I only used `ggh4x` for the flexibility it offers when it comes to tweaking positional scales when using facets. So having a geom may help to promote this handy feature. BTW: Great work by you and Allan Cameron. `geomtextpath` looks really great. Only had a short glimpse but can't barely wait to use it in action. :D – stefan Jan 29 '22 at 19:26