How do I find the area under a function in matplotlib?

I am new to python and matplotlib library, I am trying to get the area under my function line in my plot. I have a variable a

and b

that moves a rectangle in my plot. I could probably use the original math to solve this problem, but I wanted to know if there was an easier way to achieve what I am trying to do with matplotlib.

My plot looks like this

Image

I want to get the area of โ€‹โ€‹this zone

Image

If there is also an easy way to color this area, I would love to hear it too.

Here's my code to display this graph:

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 the help, sorry for the lack of embedded images.

+3


source to share


2 answers


Scipy can calculate integrals for you , which seems to be the easiest way to get what you are looking for. I think your picture and your function are not consistent with each other. Here's what I get to create your copy / paste of your function:

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

      

enter image description here



In any case, how to get the integral, taking into account the function and the boundaries of integration.

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

+1


source


Since Max Power will answer the integration part of your question, that's really good, I'll just be looking at the problem of drawing an area below / above the 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

+3


source







All Articles