问题
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?
回答1:
Adapted from the scipy.integrate.quad docs example for a different function, y = x^2:
from scipy import integrate
def f(x):
return x**2
integrate.quad(f, 0, 4)
# (21.333333333333332, 2.3684757858670003e-13)
print(4**3 / 3.) # analytical result
# 21.3333333333
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).
import sympy as sym
sym.init_printing()
_x = sym.symbols("x")
_f = sym.pi * _x**2
sym.integrate(_f, (_x, 0, 2))
Apply either of these techniques to your problem.
回答2:
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.
来源:https://stackoverflow.com/questions/43951136/calculation-of-areas-between-two-curves