Home > Net >  Colour area between 2 lines in ggplot in R?
Colour area between 2 lines in ggplot in R?

Time:03-08

Similar questions have been asked example plot

Im trying to shade in-between the red and blue lines. I tried using geom_ribbon but I cant seem to to get it to work correctly.

Any suggestions as to how I could do this?

CodePudding user response:

As you pointed out, you do want geom_ribbon:

library(ggplot2)
set.seed(100)
x <- seq(0, 20, length.out=1000)
x1 <- seq(0, 18, length.out=1000)
x2 <- seq(0, 22, length.out=1000)
dat <- data.frame(x=x, 
                  px = dexp(x, rate=0.5),
                  pxHi = dexp(x1, rate=0.5),
                  pxLo = dexp(x2, rate=0.5)
)

ggplot(dat, aes(x=x, y=px))   
  geom_ribbon(aes(x = x, ymax = pxHi, ymin = pxLo), fill = "pink")  
  geom_line()  
  geom_line(aes(x= x, y = pxHi), col = 'red')  
  geom_line(aes(x= x, y = pxLo), col = 'blue')   theme_bw()

graph

  • Related