4

I tried to find the possibilities how to shade the area between two lines in ggplot that are defined by function. I found some solutions using geom_area or geom_ribbon but in both cases you need a database in which you define ymin and ymax. Is there any other possibility? In the way that the ymin and ymax are defined also with same functions as the lines?

Here is my exsample:

myplot <- ggplot(data.frame(x=c(0, 100)), aes(x=x)) +
stat_function(fun= function(x)20*sqrt(x), geom="line", colour= "black", size= 1) +
stat_function(fun= function(x)50*sqrt(x), geom="line", colour= "black", size= 1)
myplot

enter image description here

Thank you for your help in advance.

Eco06
  • 531
  • 2
  • 8
  • 17

1 Answers1

8

Try putting the functions into the data frame that feeds the figure. Then you can use geom_ribbon to fill in the area between the two functions.

mydata = data.frame(x=c(0:100),
                    func1 = sapply(mydata$x, FUN = function(x){20*sqrt(x)}),
                    func2 = sapply(mydata$x, FUN = function(x){50*sqrt(x)}))

ggplot(mydata, aes(x=x, y = func2)) +
  geom_line(aes(y = func1)) + 
  geom_line(aes(y = func2)) + 
  geom_ribbon(aes(ymin = func2, ymax = func1), fill = "blue", alpha = .5)

enter image description here

Nancy
  • 3,989
  • 5
  • 31
  • 49