1

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?

Electrino
  • 2,636
  • 3
  • 18
  • 40

1 Answers1

5

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

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • Thanks. I think I made my example too simple. Your code works perfectly for this, but in my actual data, I keep getting an `Aesthetics must be either length 1 or the same as the data` error. I'll keep trying!! – Electrino Mar 08 '22 at 03:04
  • @Electrino you’re welcome. Yes, often times, creating a reproducible example of -your- problem is the most difficult thing to do without provide all the details of -your- problem. Maybe try masking your data? But please DO NOT modify the original question. Rather, just ask a new one. – JasonAizkalns Mar 09 '22 at 12:30