微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

求两条水平重叠曲线之间的积分

如何解决求两条水平重叠曲线之间的积分

我有一个从文本文件中绘制数据的代码。我已经能够得到每条数据曲线下的积分(虽然我不知道它们中的任何一个函数,所以我只是使用了 integral = s = simps(y,x))。两条曲线水平重叠,我想找到它们重叠的区域。我遇到了一些麻烦,因为它们水平重叠而不是垂直重叠。我要查找的区域位于此 graph 上的红线和蓝线之间。数据在 numpy 数组中,例如 bxby 代表蓝线 x 和 y,rxry 代表红线 x 和 y。我没有表示它们的函数,但它们在这些数组中。很难知道如何进行,因为它们水平重叠而不是垂直重叠。

我对此很困惑,任何帮助将不胜感激!

更新:JohanC 提供的代码worked in one case 但有 not another。非工作图最初看起来像 this(我只想要中间重叠区域的区域),但是当这也不起作用时,我尝试限制 x 范围以希望帮助代码缩小我希望计算重叠积分的区域(即范围较小的图的来源)。我目前使用的代码是提供的 JohanC 代码,如下所示:

def get_overlap_integral(bx,by,rx,ry):
    fig,ax = plt.subplots()
    ax.plot(bx,color='b')
    ax.plot(rx,ry,color='r')

    # create a common x range
    gx = np.linspace(min(bx.min(),rx.min()),max(bx.max(),rx.max()),1000)
    gby = np.interp(gx,bx,by)  # set bx,by onto the common x range
    gry = np.interp(gx,ry)  # set rx,ry onto the common x range
    gy = np.minimum(gby,gry)  # let gx,gy be the intersection of the two curves
    ax.fill_between(gx,gy,color='g',alpha=0.3)

    area = np.trapz(gy,gx)  # calculate the green area
    ax.text(0.05,0.95,f'Overlap: {area:.3f}',ha='left',va='top',transform=ax.transAxes)
    plt.show()
    return area

文本 bx、by、rx 和 ry 是如下值:

BX: [999.5 999.  998.5 ... 201.  200.5 200. ]
BY: [-3.786867e-05 -4.366451e-05 -4.745308e-05 ...  1.068685e-05  1.555391e-05
 -8.949840e-06]
RX: [999.5 999.  998.5 ... 201.  200.5 200. ]
RY: [-5.865443e-05 -7.808241e-05 -5.887286e-05 ... -1.556630e-06 -3.473830e-06
 -6.367470e-06]

我不确定为什么此功能不适用于一种情况,但可以完美适用于另一种情况。任何帮助将不胜感激!

解决方法

np.interp(new_x,old_x,old_y) 可以计算新的 x 范围的曲线。当设置在公共 x 范围上时,np.minimum 找到两条正值曲线的公共区域。 np.trapz 计算面积。

以下是一些示例代码,从创建测试数据开始:

from matplotlib import pyplot as plt
import numpy as np

# create some test data
Nb = 300
bx = np.linspace(320,750,Nb)
by = np.random.randn(Nb).cumsum()
by -= by[0]  # start at zero
by -= np.linspace(0,1,Nb) * by[-1]  # let end in zero
by = (by ** 2) ** .3  # positive curve starting and ending with zero
Nr = 200
rx = np.linspace(610,1080,Nr)
ry = np.random.randn(Nr).cumsum()
ry -= ry[0]  # start at zero
ry -= np.linspace(0,Nr) * ry[-1]  # let end in zero
ry = (ry ** 2) ** .3  # positive curve starting and ending with zero

fig,ax = plt.subplots()
ax.plot(bx,by,color='b')
ax.plot(rx,ry,color='r')

# create a common x range
gx = np.linspace(min(bx.min(),rx.min()),max(bx.max(),rx.max()),1000)
gby = np.interp(gx,bx,by)  # set bx,by onto the common x range
gry = np.interp(gx,rx,ry)  # set rx,ry onto the common x range
gy = np.minimum(gby,gry)  # let gx,gy be the intersection of the two curves
ax.fill_between(gx,gy,color='g',alpha=0.3)

area = np.trapz(gy,gx)  # calculate the green area
ax.text(0.05,0.95,f'Overlap: {area:.3f}',ha='left',va='top',transform=ax.transAxes)
plt.show()

finding the common area of two curves with different x ranges

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。