I am creating two lines with ggplot and want to shade a specific area 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 simply shades the area under the line y = 2x, and this is independent of the value of x - why?

source share