Shade region between two lines with ggplot

How about using geom_ribbon instead

ggplot(x, aes(x=x, y=twox)) + 
    geom_line(aes(y = twox)) + 
    geom_line(aes(y = x2)) +
    geom_ribbon(data=subset(x, 2 <= x & x <= 3), 
          aes(ymin=twox,ymax=x2), fill="blue", alpha=0.5) +
    scale_y_continuous(expand = c(0, 0), limits=c(0,20)) +
    scale_x_continuous(expand = c(0, 0), limits=c(0,5)) + 
    scale_fill_manual(values=c(clear,blue))

plot


I think that geom_ribbon is the way to go. There are 2 steps to go:

  1. Data Manipulation: You should manipulate data to define ymin & ymax for arguments in geom_ribbon
  2. Draw plot with geom_ribbon.

Let's see my example:

#Data 
library(gcookbook) 
# Data Manipulation
cb <-subset(climate,Source=="Berkeley")
cb$valence[cb$Anomaly10y >= 0.3] <- "pos"
cb$valence[cb$Anomaly10y < 0.3]  <- "neg"
cb$min <- ifelse(cb$Anomaly10y >= 0.3, 0.3, cb$Anomaly10y)
cb$max <- ifelse(cb$Anomaly10y >= 0.3, cb$Anomaly10y, 0.3)

#Drawing plot
ggplot(cb,aes(x=Year,y=Anomaly10y)) +
geom_ribbon(aes(ymin = min, ymax = max, fill = valence), alpha = 0.75) +
scale_fill_manual(values = c("blue", "orange")) +
geom_line(aes(col = valence), size = 1) +
scale_color_manual(values = c("blue", "orange")) +
geom_hline(yintercept=0.3, col = "blue") +
theme_bw()

Tags:

R

Ggplot2

Fill