r - 如何在R中找到两个密度与ggplot2的交集

标签 r ggplot2

如何找到使用 ggplot2 创建的两个密度图的交集?

来自名为combined 的数据框的示例:

futureChange direction

2009-10-26    0.9980446      long

2008-04-28    1.0277389  not long

2012-07-09    1.0302413  not long

2010-11-15    1.0017247  not long

我使用这段代码创建了密度图。

ggplot(combined, aes(futureChange, fill = direction))  
 geom_density(alpha = 0.2) 
 ggtitle(paste(symbol,"Long SB Frequency",sep=" "))

我想找到粉色密度线与蓝色密度线相交的位置。

我看到其他提到 intersect 函数的帖子,但我不知道如何使用密度 ggplot2 因为我没有密度载体。

最佳答案

ggplot2 中的stat_density 函数使用了 R 的 density 函数。使用 density 函数将为我们提供明确的密度估计值,我们可以使用它来找到交点(我在这里生成数据,因为给定的数据不足以执行密度计算):

set.seed(10)
N <- 100
combined <- data.frame(futureChange = c(rnorm(N, mean = -1), rnorm(N, mean = 1)),
                       direction = rep(c("long", "not long"), each = N))

lower.limit <- min(combined$futureChange)
upper.limit <- max(combined$futureChange)
long.density <- density(subset(combined, direction == "long")$futureChange, from = lower.limit, to = upper.limit, n = 2^10)
not.long.density <- density(subset(combined, direction == "not long")$futureChange, from = lower.limit, to = upper.limit, n = 2^10)

density.difference <- long.density$y - not.long.density$y
intersection.point <- long.density$x[which(diff(density.difference > 0) != 0) + 1]

ggplot(combined, aes(futureChange, fill = direction)) + geom_density(alpha = 0.2) + 
  geom_vline(xintercept = intersection.point, color = "red")

逐步采取这一步骤,我们首先计算应计算每个组的密度的限制(lower.limitupper.limit)。我们这样做是因为我们需要这些范围对于两个密度计算是相同的,以便我们以后可以比较它们。此外,我们使用 density 函数中的 n 参数指定计算密度的点数(如果您想要更准确的结果,请增加此值)。

接下来,我们计算数据中每个组的密度。然后我们想找到交点,这样我们就可以计算出密度的差异,看看它什么时候从正切换到负,反之亦然。命令 which(diff(density.difference > 0) != 0) + 1 将为我们提供这些开关发生的索引(由于差异,我们添加一个),因此我们可以得到通过在 long.density$x (或 not.long.density$x 因为它们在构造上相同)中取相应的值来计算该交集的值。

enter image description here

关于r - 如何在R中找到两个密度与ggplot2的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453706/

相关文章:

r - 在 R 中粘贴 0 个常规和斜体文本

r - 如何将 Theil-Sen 方法与 geom_smooth 一起使用

r - 注释绘图边缘而不更改绘图限制或将 "expand"设置为 0

删除重复项需要转置,但我的数据框太大

r - 在 ggplot2 中;在这种情况下,如何将 x 轴移动到顶部,然后使用 coord_flip () 旋转轴?

r - r语言如何给hadoop用户root权限

r - 按行索引(数据的原始顺序)而不是按字母顺序设置 ggplot 中 x 或 y 的顺序

r - R 中每个类别的总和值的条形图 - 当前仅绘制最高值

r - 为什么在我尝试使用 ggplot2 显示分面线图时显示 geom_path 警告消息?

mysql - R中的多个数据库连接