rggplot2

Shade area under and above the curve function in ggplot


I have a function and its domain of this function is (-100, 100)

fun.1 <- function(x) (-100*x)/(x+100)

Here is my code how I draw a function.

ggplot(data.frame(x = c(-50,50)), mapping = aes(x=x)) + stat_function(fun = fun.1, color = "black", size = 1)

I would like to shade the area under the curve of this function in "red" color and above this function in "green" color. Can anyone have an idea how to do it?

Thank you.


Solution

  • It's probably easiest to create a data frame of x and y first using your function, rather than passing your function through ggplot2.

    x <- -50:50
    y <- fun.1(x)
    df <- data.frame(x,y)
    

    The plotting can be done via 2 geom_ribbon objects (one above and one below), which can be used to fill an area (geom_area is a special case of geom_ribbon), and we specify ymin and ymax for both. The bottom specifies ymax=y and ymin=-Inf and the top specifies ymax=Inf and ymin=y. Finally, since df$y changes along df$x, we should ensure that any arguments referencing y are contained in aes().

    ggplot(df, aes(x,y)) + theme_minimal() +
      geom_line(size=1) +
      geom_ribbon(ymin=-Inf, aes(ymax=y), fill='red', alpha=0.2) +
      geom_ribbon(aes(ymin=y), ymax=Inf, fill='green', alpha=0.2)
    

    enter image description here