RenZhen95
RenZhen95

Reputation: 43

Is there a way in Python to calculate the overlapping area between multiple curves?

While calculating the overlapping area between two curves is something that has been addressed many times, I am yet to find a solution for calculating the overlapping areas between multiple curves, i.e. 4 curves.

Plot of 4 curves

Anybody out there with an elegant solution?

Upvotes: 2

Views: 1611

Answers (1)

JohanC
JohanC

Reputation: 80279

You can take the minimum (np.amin) of the 4 curves and calculate its area (e.g. via np.trapz). If the curves don't have a common x, they first need to be recalculated using a shared x (e.g. using 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()

area under 4 curves

Upvotes: 12

Related Questions