I'm finding the area under a set of curves using np.trapz
function and
I want to plot the overlapping area under these curves
import numpy as np
x0 = [0, 4, 6, 10, 15, 20]
y0 = [18, 17.5, 13, 12, 8, 10]
x1 = [0, 10.5, 28]
y1 = [18.2, 10.6, 10.3]
x2 = [0, 4, 6, 10, 15, 20]
y2 = [18, 13, 15, 12, 11, 9.6]
x3 = [9, 17, 28]
y3 = [5, 5.5, 7]
x4 = [1, 10, 20]
y4 = [3, 0.8, 2]
x = [x0,x1,x2,x3,x4]
y = [y0,y1,y2,y3,y4]
# compute overlapping area
xmin = -np.inf
xmax = np.inf
for i in range(5):
area = np.trapz(y[i], x[i])
plt.plot(x[i], y[i], label=i)
xmin = max(xmin, min(x[i]))
xmax = min(xmax, max(x[i]))
# y_intersection = np.amin(y, axis=0)
# print(y_intersection)
# 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()
plt.show()
I want to plot something like the below
Could someone please help me with this?
You almost did it with fill_between
but the parameters were wrong. Do as below:
import numpy as np
x0 = [0, 4, 6, 10, 15, 20]
y0 = [18, 17.5, 13, 12, 8, 10]
x1 = [0, 10.5, 28]
y1 = [18.2, 10.6, 10.3]
x2 = [0, 4, 6, 10, 15, 20]
y2 = [18, 13, 15, 12, 11, 9.6]
x3 = [9, 17, 28]
y3 = [5, 5.5, 7]
x4 = [1, 10, 20]
y4 = [3, 0.8, 2]
x = [x0,x1,x2,x3,x4]
y = [y0,y1,y2,y3,y4]
# compute overlapping area
xmin = -np.inf
xmax = np.inf
for i in range(5):
area = np.trapz(y[i], x[i])
plt.plot(x[i], y[i])
plt.fill_between(x[i], y[i], ec='black', alpha=0.5, label=f'data {i+1}: {area:.3f}')
plt.legend()
plt.show()