【问题标题】:Find value of x that will equally devide overlap between two curves找到将相等地划分两条曲线之间重叠的 x 值
【发布时间】:2019-04-12 15:35:34
【问题描述】:

使用@Ramnath 在this 上一个问题中的答案中的一些代码,我想找到 x 的值,它将平均分配两条曲线之间的重叠区域。请参阅以下示例:

library(ggplot2)
x  = seq(-7, 10, length = 200)
y1 = dnorm(x, mean = 0,sd = 1)
y2 = dnorm(x, mean = 3,sd = 2)

mydf = data.frame(x, y1, y2)

p0 = ggplot(mydf, aes(x = x)) +                         
  geom_line(aes(y = y1), colour = 'blue') +
  geom_line(aes(y = y2), colour = 'red') +
  geom_area(aes(y = pmin(y1, y2)), fill = 'gray60')

任何建议将不胜感激!

【问题讨论】:

    标签: r math ggplot2 curve calculus


    【解决方案1】:

    在下面的方法中,我们找到重叠的累积面积,然后找到这个累积面积为总重叠面积一半的 x 值。

    为了说明,我添加了额外的数据列来标记所有步骤,但如果您只想直接找到分界线的位置,则没有必要。

    # overlap
    mydf$overlap = apply(mydf[,c("y1","y2")], 1, min)
    
    # area of overlap
    mydf$overlap.area = cumsum(mydf$overlap * median(diff(mydf$x)))
    
    # Find x that divides overlap area in half
    
    # Method 1: Directly from the data. Could be inaccurate if x values are
    #  not sufficiently close together.
    x0a = mydf$x[which.min(abs(mydf$overlap.area - 0.5*max(mydf$overlap.area)))]
    
    # Method 2: Use uniroot function to find x value where cumulative overlap 
    #  area is 50% of total overlap area. More accurate.
    
    # First generate an interpolation function for cumulative area.
    #  Subtract half the cumulative area so that function will cross
    #  zero at the halfway point
    f = approxfun(mydf$x, mydf$overlap.area - 0.5*max(mydf$overlap.area))
    
    # Find x value at which interpolation function crosses zero
    x0b = uniroot(f, range(mydf$x))$root
    
    p0 = ggplot(mydf, aes(x = x)) +                         
      geom_line(aes(y = y1), colour = 'blue') +
      geom_line(aes(y = y2), colour = 'red') +
      geom_area(aes(y = pmin(y1, y2)), fill = 'gray60') +
      geom_line(aes(y=overlap), colour="purple") +
      geom_line(aes(y=overlap.area), colour="green") +
      geom_vline(xintercept=c(x0a,x0b), color=c("orange","darkgreen"), 
                 linetype=c("solid", "dashed")) +
      theme_classic()
    p0
    

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2019-08-06
      • 2014-06-23
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多