2

I have following simulated data of following 2 variables. I created the density plot as follows,

set.seed(1)
x1=density(rnorm(100,0.5,3))
x2=density(rnorm(100,1,3))

plot(x1)
lines(x2)

enter image description here

Is there any function that can use to find the common area for these 2 graphs using R ?

Do i need to perform an integration for intersecting points ?

Thank you

alistaire
  • 42,459
  • 4
  • 77
  • 117
student_R123
  • 962
  • 11
  • 30
  • 1
    Possible duplicate of [calculate area of overlapping density plot by ggplot using R](https://stackoverflow.com/questions/41914257/calculate-area-of-overlapping-density-plot-by-ggplot-using-r) – Matt Jun 30 '19 at 23:27

1 Answers1

3

If you set the sequence both densities use for x values to be identical, you can use pmin on the y values. (Call str(x1) to see how they're stored.) For instance, to see how it works:

set.seed(1)
x1 <- density(rnorm(100,0.5,3), from = -10, to = 10, n = 501)
x2 <- density(rnorm(100,1,3), from = -10, to = 10, n = 501)

plot(x2, main = 'Density intersection')
lines(x1)
polygon(x1$x, pmin(x1$y, x2$y), 20, col = 'dodgerblue')

density intersection

Taking the integral means just multiplying each pmin times the increment in the x sequence and summing the lot:

sum(pmin(x1$y, x2$y) * diff(x1$x[1:2]))
#> [1] 0.896468
alistaire
  • 42,459
  • 4
  • 77
  • 117