[R] Determine area between two density plots

Ralf B ralf.bierig at gmail.com
Thu Sep 23 18:27:34 CEST 2010

I wonder what the best way is to access those values. I am using the
following code:

x1 <- c(1,2,1,3,5,6,6,7,7,8)
x2 <- c(1,2,1,3,5,6,5,3,8,7)
d1 <- density(x1, na.rm = TRUE)
d2 <- density(x2, na.rm = TRUE)
plot(d1, lwd=3, main="bla")
lines(d2, lty=2, lwd=3)

The last two lines allow me to access 1000 values, but I don't know if
this is the right approach. I also don't know why they are in two
columns. Does density have a saver way to get to those values?



On Wed, Sep 22, 2010 at 5:25 PM, Peter Alspach
<Peter.Alspach at plantandfood.co.nz> wrote:
> Tena koe Ralf
> If you save the results of density()
> x1Den <- density(x1)
> you get the x and y values of the line which is plotted.  Similarly for x2 - you can then use these to shade the joint area and find the area.  Tinkering with the arguments of density to make the x values for each the same will make this process easier.  Let me know if you'd like more details.
> HTH ....
> Peter Alspach
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
>> project.org] On Behalf Of Ralf B
>> Sent: Thursday, 23 September 2010 8:55 a.m.
>> To: r-help Mailing List
>> Subject: [R] Determine area between two density plots
>> Hi group,
>> I am creating two density plots as shown in the code below:
>> x1 <- c(1,4,5,3,2,3,4,5,6,5,4,3,2,1,1,1,2,3)
>> x2 <- c(1,4,5,3,5,7,4,5,6,1,1,1,2,1,1,1,2,3)
>> plot(density(x1, na.rm = TRUE))
>> polygon(density(x2, na.rm = TRUE), border="blue")
>> How can I determine the area that is covered between the two plots as
>> a number and how can I grey (or highlight with a pattern) the area
>> that lies between the two lines?
>> Thanks,
>> Ralf
>> ______________________________________________
>> 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.
> The contents of this e-mail are confidential and may be subject to legal privilege.
>  If you are not the intended recipient you must not use, disseminate, distribute or
>  reproduce all or any part of this e-mail or attachments.  If you have received this
>  e-mail in error, please notify the sender and delete all material pertaining to this
>  e-mail.  Any opinion or views expressed in this e-mail are those of the individual
>  sender and may not represent those of The New Zealand Institute for Plant and
>  Food Research Limited.

More information about the R-help mailing list