Electrino
Electrino

Reputation: 2900

Colour area between 2 lines in ggplot in R?

Similar questions have been asked here and here, but I can't seem to get them to work for my example. If I have a plot that looks something like this:

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_line() +
  geom_line(aes(x= x, y = pxHi), col = 'red') +
  geom_line(aes(x= x, y = pxLo), col = 'blue') + theme_bw()

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?

Upvotes: 1

Views: 92

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20483

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

Upvotes: 5

Related Questions