I have a code contain a curve and a line. I know how to fill the areas below and under the line but I need to calculate the areas values of each one.
Here is the code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = 0*x
fig, ax = plt.subplots(1, 1, sharex=True)
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True)
ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
plt.show()
Any help?
Adapted from the
scipy.integrate.quad
docs example for a different function, y = x^2:The result and an error for the numerical calculation is returned.
If you want an exact or symbolic answer, consider
sympy
. Here is a similar example applied to y = πx^2 (Note: leading underscores were used here to distinguish Sympy objects).Apply either of these techniques to your problem.
This is called numerical-integration. There's a bunch of standard methods. As @pylang said they're already implemented in
scipy.integrate.*
.scipy.integrate.quad
is Gaussian quadrature.