Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
RenZhen95 Avatar asked Nov 18 '25 00:11

RenZhen95


1 Answers

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

like image 186
JohanC Avatar answered Nov 20 '25 15:11

JohanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!