[R] highlight overlapping region of two densities

Rui Barradas ruipbarradas at sapo.pt
Wed Mar 20 16:03:23 CET 2013


Hello,

Try the following.



d0 <- density(myd)
d1 <- density(myd1)

idx0 <- d0$x >= 1 & d0$x <= 4
idx1 <- d1$x >= 1 & d1$x <= 4
yy <- apply(cbind(d0$y[idx0], d1$y[idx1]), 1, min)
xx <- d0$x[idx0]
xx <- c(xx[1], xx, xx[1])
yy <- c(0, yy, 0)

polygon(xx, yy, col = "blue")


Hope this helps,

Rui Barradas

Em 20-03-2013 12:32, andrija djurovic escreveu:
> Hi all.
>
> I would like to highlight overlapping regions of two densities and I could
> not find a way to do it.
>
> Here is the sample code:
>
> myd <- c(2,4,5, 4,3,2,2,3,3,3,2,3,3,4,2,4,3,3,3,2,2.5,
>           2, 3,3, 2.3, 3, 3, 2, 3)
> myd1 <- myd-2
> plot(range(density(myd)$x, density(myd1)$x), range(density(myd)$y,
> density(myd1)$y), type = "n")
> lines(density(myd), col=1, lwd=4)
> lines(density(myd1), col=2, lwd=4, lty=2)
>
> So, I am trying to highlight the region from 1 to 4, on x axis, taking the
> minimum value of corresponding y values.
>
> I am aware of polygon function but don't know how to define correctly x and
> y coordinate vectors for this function.
>
> Could someone help me to solve this?
>
> Thank in advance.
>
> Andrija
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list