Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use polygon() to shade below a probability density curve

Tags:

plot

r

I'm having trouble getting polygon() to shade below the distribution all the way to the x-axis. It seems to shade above the exponential distribution to a y=-x line. Here is where what I have so far:

x <- seq(0,50,0.01)
y <- dexp(seq(0,50,0.01),rate=0.11)
plot(x, y, type="l", col=col2rgb("yellow",0.5), xaxs="i", yaxs="i", ylim=c(0,0.15))
polygon(x, y ,border=NA,col=col2rgb("yellow",0.5))

bad shade

Thanks so much!

like image 320
John Avatar asked May 26 '16 22:05

John


1 Answers

Solution is simple, by adding (0,0) to the vertices of the polygon. See below:

x <- seq(0,50,0.01)
y <- dexp(seq(0,50,0.01),rate=0.11)
plot(x, y, type="l", col=col2rgb("yellow",0.5), xaxs="i", yaxs="i", ylim=c(0,0.15))
polygon(c(0, x), c(0, y), border=NA, col=col2rgb("yellow",0.5))

shade


How polygon() works

polygon() will line up all vertices in order. The problem of your original code is that the origin (0, 0) is not one of the vertices, so it will not be part of the polygon. You can also consider the following toy example:

x0 <- c(0, 0.5, 1.5)
y0 <- c(1.5, 0.5, 0)
## triangle, with three vertices
plot(x0, y0, pch = ".")
polygon(x0, y0, col = "red", border = NA)
## area under triangle, four vertices
polygon(c(0, x0), c(0, y0), col = "yellow", border = NA)

toy example

like image 139
Zheyuan Li Avatar answered Sep 28 '22 03:09

Zheyuan Li