Hi如何计算R中两列(或一列的两个子集)之间的重叠面积。请参阅以下示例数据:
set.seed(1234)
df <- data.frame(
Data=factor(rep(c("D1", "D2"), each=200)),
weight=round(c(rnorm(200, mean=55, sd=5),
rnorm(200, mean=65, sd=5)))
)
library(ggplot2)
plot <- ggplot(df, aes(weight,fill = Data))+
geom_density()
plot
这就产生了下面的图。我想知道,如何给重叠区域着色并计算重叠系数(OVL),类似于使用蒙特卡洛积分here所做的那样?请注意,当我询问是否有观测值的数据集时,提供的链接(和上面的示例)使用了参数分布。
发布于 2020-11-18 04:56:46
通常,我发现直接使用密度并将其绘制为geom_area
更容易。如果在两个分布上获得匹配的x轴采样点,则可以使用pmin
找到重叠区域,其值的总和除以两条曲线的值的总和应该会得到重叠的总面积的比例。
d1dens <- with(df, density(weight[Data == "D1"],
from = min(weight),
to = max(weight)))
d2dens <- with(df, density(weight[Data == "D2"],
from = min(weight),
to = max(weight)))
joint <- pmin(d1dens$y, d2dens$y)
df2 <- data.frame(x = rep(d1dens$x, 3),
y = c(d1dens$y, d2dens$y, joint),
Data = rep(c("D1", "D2", "overlap"), each = length(d1dens$x)))
ggplot(df2, aes(x, y, fill = Data)) +
geom_area(position = position_identity(), color = "black") +
scale_fill_brewer(palette = "Pastel2") +
theme_bw()
sum(joint) / sum(d1dens$y, d2dens$y)
#> [1] 0.1480701
https://stackoverflow.com/questions/64882496
复制相似问题