Find the area between two curves plotted in matplotlib (fill_between area)

F4R picture F4R · Aug 22, 2014 · Viewed 15.2k times · Source

I have a list of x and y values for two curves, both having weird shapes, and I don't have a function for any of them. I need to do two things: (1) plot it and shade the area between the curves like the image below; (2) find the total area of this shaded region between the curves.

I'm able to plot and shade the area between those curves with fill_between and fill_betweenx in matplotlib, but I have no idea on how to calculate the exact area between them, specially because I don't have a function for any of those curves.

Any ideas?

I looked everywhere and can't find a simple solution for this. I'm quite desperate, so any help is much appreciated.

Thank you very much!

Area between curves - how to calculate the area of the shaded region without curve's function?


EDIT: For future reference (in case somebody runs into the same problem), here is how I solved this (many months later): connected the first and last node/point of each curve together, resulting in a big weird-shaped polygon, then used shapely to calculate the polygon's area automatically, which is the exact area between the curves, no matter which way they go or how nonlinear they are. Works like a charm, ran for thousands of curves already. :)

Here is my code:

from shapely.geometry import Polygon

x_y_curve1 = [(0.121,0.232),(2.898,4.554),(7.865,9.987)] #these are your points for curve 1 (I just put some random numbers)
x_y_curve2 = [(1.221,1.232),(3.898,5.554),(8.865,7.987)] #these are your points for curve 2 (I just put some random numbers)

polygon_points = [] #creates a empty list where we will append the points to create the polygon

for xyvalue in x_y_curve1:
    polygon_points.append([xyvalue[0],xyvalue[1]]) #append all xy points for curve 1

for xyvalue in x_y_curve2[::-1]:
    polygon_points.append([xyvalue[0],xyvalue[1]]) #append all xy points for curve 2 in the reverse order (from last point to first point)

for xyvalue in x_y_curve1[0:1]:
    polygon_points.append([xyvalue[0],xyvalue[1]]) #append the first point in curve 1 again, to it "closes" the polygon

polygon = Polygon(polygon_points)
area = polygon.area
print(area)

Answer

JulienD picture JulienD · Aug 22, 2014

Define your two curves as functions f and g that are linear by segment, e.g. between x1 and x2, f(x) = f(x1) + ((x-x1)/(x2-x1))*(f(x2)-f(x1)). Define h(x)=abs(g(x)-f(x)). Then use scipy.integrate.quad to integrate h.

That way you don't need to bother about the intersections. It will do the "trapeze summing" suggested by ch41rmn automatically.