rggplot2geom-ribbon

GGplot geom_ribbon - Only color between 2 points


I have 2 sets of numerical data (called L.MEAN and P.MEAN) plotted as 2 lines on the same plot (with the same x axis, Time). I want to color the space between the lines and the space between the lower line (P.MEAN) and the x axis, but only within a certain range of x (between WIT and WOT). For clarity, WIT and WOT are just numbers that I obtained through the which() function.

This is what I have written:

library(ggplot2)
library(tidyverse)
data %>% ggplot(aes(x = Time)) +
  geom_line(aes(y = L.MEAN, color = "deepskyblue3"), linewidth = 1) +
  geom_line(aes(y = P.MEAN, color = "deeppink"), linewidth = 1) +
  geom_ribbon(aes(ymin = P.MEAN,
                  ymax = L.MEAN,
                  xmin = WIT,
                  xmax = WOT),
              alpha = 0.4,
              fill = "deepskyblue") +
  geom_ribbon(aes(ymin = 0,
                  ymax = P.MEAN,
                  xmin = WIT,
                  xmax = WOT),
              alpha = 0.4,
              fill = "deeppink")

Unfortunately, it doesn't seem to work, as it colors the entire x axis. enter image description here

Could someone please tell me what I'm doing wrong?


Solution

  • If you want to color only a range of your chart, then you have to filter the data used for geom_ribbon for the desired range. Additionally I fixed the assignments of the colors for the lines by setting the colors via scale_color_manual.

    Using some fake random example data:

    library(ggplot2)
    
    set.seed(123)
    data <- data.frame(
      Time = seq_len(125),
      L.MEAN = runif(125, 50, 100),
      P.MEAN = runif(125, 25, 50)
    )
    
    WIT <- 35
    WOT <- 70
    
    ggplot(data, aes(x = Time)) +
      geom_line(aes(y = L.MEAN, color = "lmean"), linewidth = 1) +
      geom_line(aes(y = P.MEAN, color = "pmean"), linewidth = 1) +
      geom_ribbon(
        data = ~ subset(.x, Time >= WIT & Time <= WOT),
        aes(
          ymin = P.MEAN,
          ymax = L.MEAN
        ),
        alpha = 0.4,
        fill = "deepskyblue"
      ) +
      geom_ribbon(
        data = ~ subset(.x, Time >= WIT & Time <= WOT),
        aes(
          ymin = 0,
          ymax = P.MEAN
        ),
        alpha = 0.4,
        fill = "deeppink"
      ) +
      scale_color_manual(
        values = c(lmean = "deepskyblue", pmean = "deeppink")
      )