Reputation: 43
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.
Anybody out there with an elegant solution?
Upvotes: 2
Views: 1611
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()
Upvotes: 12