Alfonso Santiago
Alfonso Santiago

Reputation: 531

Computing the area filled by matplotlib.pyplot.fill(...)

I'd like to compute the area inside of a curve defined by two vectors a and b. For your reference the curve looks something like this (pyplot.plot(a,b)):

curve to compute area

I saw matplotlib has a fill functionality that let you fill the area enclosed by the curve:

enter image description here

I'm wondering, there's any way to obtain the area filled using that same function? It would be very useful as the other way I'm thinking of computing that area is through numerical integration, much more cumbersome.

Thank you for your time.

Upvotes: 1

Views: 1249

Answers (1)

jordiplam
jordiplam

Reputation: 66

If you really want to find the area that was filled by matplotlib.pyplot.fill(a, b), you can use its output as follows:

def computeArea(pos):
    x, y = (zip(*pos))
    return 0.5 * numpy.abs(numpy.dot(x, numpy.roll(y, 1)) - numpy.dot(y, numpy.roll(x, 1)))

# pyplot.fill(a, b) will return a list of matplotlib.patches.Polygon.
polygon = matplotlib.pyplot.fill(a, b)

# The area of the polygon can be computed as follows:
# (you could also sum the areas of all polygons in the list).
print(computeArea(polygon[0].xy))

This method is based on this answer, and it is not the most efficient one.

Upvotes: 1

Related Questions