Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shaded area under two curves using R

Tags:

plot

r

I wrote the following code in R

x=seq(-7,10,length=200)
y1=dnorm(x,mean=0,sd=1)
plot(x,y1,type="l",lwd=2,col="red")
y2=dnorm(x,mean=3,sd=2)
lines(x,y2,type="l",lwd=2,col="blue")

How can I shade the area under both curves (known as the overlap between the two curves).

I will highly appreciate any suggestions.

like image 589
Muna Avatar asked Jul 22 '11 07:07

Muna


People also ask

How do I shade under a curve in R?

The polygon function can be used to shade the area under the density curve. You just need to pass the density object to it and specify a color.

How do you shade a graph in R?

Method 1: Shade a graph using polygon function : In this method, we are calling the polygon function with its argument col passed with the name or the hex code of the color needed to be shaded in the given graph.


2 Answers

Oh, well, @SachaEpskamp beat me to it, but here is my much less elegant solution.

shade_under_curve <- function(fun, xmin, xmax, length=100){
  xvals <- seq(xmin, xmax, length=length)
  dvals <- match.fun(fun)(xvals)
  polygon(c(xvals,rev(xvals)),c(rep(0,length),rev(dvals)),col="gray")
}


y1 <- function(x)sapply(x, function(xt)dnorm(xt,mean=0,sd=1))
y2 <- function(x)sapply(x, function(xt)dnorm(xt,mean=3,sd=2))

my.fun <- function(x){sapply(x, function(xt)min(y1(xt), y2(xt)))}

Edit to include initial plot:

plot(y1, -10, 10, col="red")
curve(y2, add=TRUE, col="blue")
shade_under_curve(my.fun, -10, 10, length=1000)

enter image description here

like image 62
Andrie Avatar answered Oct 24 '22 22:10

Andrie


Add the following line:

polygon(x,pmin(y1,y2),col="gray")

This basically works exactly like the pen tool in photoshop, where the first vector, x are the x-coordinates and the second vector, pmin(y1,y2) are the y coordinates. pmin gives you a vector with the minimal values of two vectors elementwise, which corresponds to the y coordinates of the top of the overlap.

EDIT:

I prefer using curve() (as Andrie suggested), which can be used to plot a function. You can save it's coordinates while plotting too and us it in exactly the same way:

fun1 <- curve(dnorm(x,mean=0,sd=1),type="l",lwd=2,col="red")
fun2 <- curve(dnorm(x,mean=3,sd=2),type="l",lwd=2,col="blue",add=TRUE)
polygon(fun1$x,pmin(fun1$y,fun2$y),col="gray")
like image 25
Sacha Epskamp Avatar answered Oct 25 '22 00:10

Sacha Epskamp