rggplot2gradientgeom-ribbon

Fill area between two lines with different colors based on condition in ggplot2 R


I have data with the monthly mean temperature in current year and the historical mean temperature of each month. I just want to fill the area (this area represents temperature anomaly between current year and historical data) between both lines. If temperature anomaly is positive then area should be painted in red; if temperature anomaly is negative then it should be painted in blue

Data:

df <- data.frame(
  month = c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"),
  tmean = c(20, 22, 20, 28, 30, 32, 34, 33, 30, 27, 24, 18),
  tmean_ref = c(18, 20, 23, 27, 29, 31, 33, 32, 29, 26, 22, 19),
  tano = c(2, 2, -3, 1, 1, 1, 1, 1, 1, 1, 2, -1),
  tano_label = c("+2", "+2", "-3", "+1", "+1", "+1", "+1", "+1", "+1", "+1", "+2", "-1")
)

My code so far:

  ggplot2::ggplot(data = df, aes(x = month, y = tmean, group = 1)) +
    ggplot2::geom_line(linewidth = 0.85, lineend = "round", na.rm = TRUE) +
    ggplot2::geom_line(aes(y = tmean_ref, group = 1), linetype = "longdash", na.rm = TRUE) +
    ggplot2::geom_point(na.rm = TRUE) +
    ggrepel::geom_label_repel(aes(label = tano_label), segment.color = NA, na.rm = TRUE)

enter image description here

Basically, if solid line is above dotted line then area should be red, if solid line is below dotted line then area should be blue. It would be awesome to have gradient colors too (higher anomaly -> higher red/blue)

Thanks in advance!


Solution

  • Gradient fills mapped to data are hard to achieve in ggplot; I would probably use a bunch of segments here to achieve this:

    library(tidyverse)
    
    df <- df %>% 
      mutate(month = as.numeric(month))
    
    df2 <- df %>%
      reframe(x = seq(1, 12, length = 500),
              y1 = approx(month, tmean, xout = x)$y,
              y2 = approx(month, tmean_ref, xout = x)$y,
              diff = y1 - y2)
    
    ggplot(df, aes(x = month, y = tmean)) +
      geom_segment(aes(x = x, y = y1, xend = x, yend = y2, color = diff),
                   data = df2, linewidth = 1) +
      geom_line(linewidth = 0.85, lineend = "round", na.rm = TRUE) +
      geom_line(aes(y = tmean_ref, group = 1), linetype = "longdash", na.rm = TRUE) +
      geom_point(na.rm = TRUE) +
      ggrepel::geom_label_repel(aes(label = tano_label), 
                                segment.color = NA, na.rm = TRUE) +
      scale_color_gradientn(colors = c('red', 'gray', 'green4')) +
      scale_x_continuous(breaks = 1:12)
    

    enter image description here