Calculate the area of ​​the overlapping density plot using ggplot using R

How can I get an area with overlapping density curves?

How can I solve the problem with R? (There is a solution for python here: Calculate the overlap area of ​​two functions )

set.seed(1234)
df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
  )

(Source: http://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization )

ggplot(df, aes(x=weight, color=sex, fill=sex)) + 
 geom_density(aes(y=..density..), alpha=0.5)

"The points used on the chart are returned by ggplot_build (), so you can access them." So now I have points, and I can feed them, but my problem is that I do not know how to subtract the density functions.

Any help is much appreciated! (And I believe in high demand, there is no solution for this readily available.)

+2
2

R-, . , , .

, .

##  Create the two density functions and display
FDensity = approxfun(density(df$weight[df$sex=="F"], from=40, to=80))
MDensity = approxfun(density(df$weight[df$sex=="M"], from=40, to=80))
plot(FDensity, xlim=c(40,80), ylab="Density")
curve(MDensity, add=TRUE)

## Solve for the intersection and plot to confirm
FminusM = function(x) { FDensity(x) - MDensity(x) }
Intersect = uniroot(FminusM, c(40, 80))$root
points(Intersect, FDensity(Intersect), pch=20, col="red")

Intersection of density plots

, .

integrate(MDensity, 40,Intersect)$value + 
    integrate(FDensity, Intersect, 80)$value
[1] 0.2952838
+1

, 5878028. , R noob, :

"" ( ) "" ( ):

library(overlapping)
library(lattice)

"x" , , . "data1" "data2" " ":

x <- list(X1=yourfile$data1, X2=yourfile$data2)

, , %:

out <- overlap(x, plot=TRUE)

, -, !

overlapping plot

0

All Articles