【问题标题】:Is there a way in Python to calculate the overlapping area between multiple curves?Python中有没有办法计算多条曲线之间的重叠面积?
【发布时间】:2021-12-02 19:17:02
【问题描述】:

虽然计算两条曲线之间的重叠面积已被多次解决,但我还没有找到计算多条曲线之间重叠面积的解决方案,即 4 条曲线。

有人有优雅的解决方案吗?

【问题讨论】:

  • 如果您在相同的 x 点处对所有曲线进行了采样,那么您可以为每个 x 点取最小值。如果经过精细采样,它应该是一个足够好的近似值。

标签: python numpy math scipy


【解决方案1】:

您可以取 4 条曲线中的最小值 (np.amin) 并计算其面积(例如,通过 np.trapz)。如果曲线没有公共 x,则首先需要使用共享 x 重新计算它们(例如使用 np.interp)。

from matplotlib import pyplot as plt
from scipy.stats import gaussian_kde
import numpy as np

data = np.random.rand(6, 4) ** 3
x = np.linspace(-1, 2, 200)
ys = []
for label in range(4):
    kde_func = gaussian_kde(data[:, label])
    y = kde_func(x)
    plt.plot(x, y, label=label)
    ys.append(y)
y_intersection = np.amin(ys, axis=0)
area = np.trapz(y_intersection, x)
fill_poly = plt.fill_between(x, 0, y_intersection, fc='yellow', ec='black', alpha=0.5,
                             label=f'intersection: {area:.3f} ')
fill_poly.set_hatch('xxx')
plt.legend()

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 2017-10-12
    • 2018-02-11
    • 2014-06-21
    • 2019-02-07
    • 2013-02-27
    相关资源
    最近更新 更多