Shade region between two lines with ggplot

user2568648 picture user2568648 · Feb 18, 2015 · Viewed 36.5k times · Source

I produce the folowing two lines with ggplot and would like to shade a specific region between the two lines i.e. where y=x² is greater than y=2x, where 2 <= x <= 3.

# create data #

x<-as.data.frame(c(1,2,3,4))
colnames(x)<-"x"
x$twox<-2*x$x
x$x2<-x$x^2

# Set colours #

blue<-rgb(0.8, 0.8, 1, alpha=0.25)
clear<-rgb(1, 0, 0, alpha=0.0001)

# Define region to fill #

x$fill <- "no fill"
x$fill[(x$x2 > x$twox) & (x$x <= 3 & x$x >= 2)] <- "fill"

# Plot #

ggplot(x, aes(x=x, y=twox)) + 
  geom_line(aes(y = twox)) + 
  geom_line(aes(y = x2)) +
  geom_area(aes(fill=fill)) +
  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))

The result is the following which just shades the region under the line y=2x, and this no matter what the x-value - why?

enter image description here

Answer

Tobias Madsen picture Tobias Madsen · Feb 18, 2015

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