Drakota
Drakota

Reputation: 357

How to find the area below a function in matplotlib?

I'm new to python and the library matplotlib, I'm trying to get the area below my function line in my plot. I have a variable a & b that moves a rectangle in my plot. I could probably use raw math to solve this problem, but I wanted to know if there was a simpler way to achieve what I'm trying to do with matplotlib.

My plot looks like this

Image

I wish to get the area of this zone

Image

If, there's also an easy way to color this area, I'd like to hear it too.

Here's my code to display this plot :

plt.clf()
plt.draw()
plt.axis(xmin = 0, xmax = 80, ymin = 0, ymax = 5)
plt.plot(-np.cbrt(np.power(t, 2) - 16 * t + 63) +4)
currentAxis = plt.gca()
line = currentAxis.lines[0]
for x, y in zip(line.get_xdata(), line.get_ydata()):
    if x == 0 or y == 0:
        if b > a:
            currentAxis.add_patch(patches.Rectangle(((a * 80 / 11), y), (b * 80 / 11) - (a * 80 / 11), 5, fill=False))
        else:
            currentAxis.add_patch(patches.Rectangle((-(b * 80 / 11) + 80, y), -(a * 80 / 11) + (b * 80 / 11), 5, fill=False))
plt.show()

Thanks for helping, sorry for no embed images.

Upvotes: 3

Views: 5424

Answers (2)

Max Power
Max Power

Reputation: 8954

Scipy can calculate integrals for you, which seems to be the simplest way to get what you're looking for. I think your picture and your function aren't consistent with each other though. Here's what I get plotting your function copy/pasted:

t = pd.Series(range(0,80))
plt.plot(-np.cbrt(np.power(t, 2) - 16 * t + 63) +4)

enter image description here

Anyway here's how to get the integral, given a function and integration bounds.

import scipy.integrate as integrate

# define components for integral calculation
lower_bound = 22
upper_bound = 36

f = lambda t: -np.cbrt(np.power(t, 2) - 16 * t + 63) +4

# calculate integral
integral, error = integrate.quad(f, lower_bound, upper_bound)
print(integral)

-50.03118191324093

Upvotes: 1

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

Since Max Power's answer to the integration part of your question is really good, I'll just be adressing the issue of drawing the area below/above curve. You can use fill_between:

import numpy as np
from matplotlib import pyplot as plt
def f(t):
    return -np.cbrt(np.power(t, 2) - 16 * t + 63) +4

t = np.arange(0,80,1/40.)
plt.plot(t,f(t))

section = np.arange(22, 36, 1/20.)
plt.fill_between(section,f(section))

plt.axhline(0, color='k')
plt.axvline(0, color='k')
plt.show()

enter image description here

Upvotes: 3

Related Questions