如何在matplotlib中找到函数下面的区域?

时间:2017-05-16 03:12:07

标签: python math matplotlib plot

我是python和matplotlib库的新手,我正试图在我的情节中获得我的功能线下面的区域。我有一个变量a& b在我的情节中移动一个矩形。我可能会使用原始数学来解决这个问题,但我想知道是否有更简单的方法来实现我正在尝试使用matplotlib。

我的情节看起来像这样

Image

我希望得到这个区域的区域

Image

如果,还有一种简单的方法可以为这个区域着色,我也想听听它。

这是我显示此图的代码:

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()

感谢您的帮助,抱歉没有嵌入图片。

2 个答案:

答案 0 :(得分:3)

由于Max Power对问题的整合部分的回答非常好,我只是解决了绘制曲线下方/上方区域的问题。您可以使用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

答案 1 :(得分:1)

Scipy can calculate integrals for you,这似乎是获得所需内容的最简单方法。我想你的 但是图片和你的功能并不一致。这是我绘制你的功能复制/粘贴的内容:

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

enter image description here

无论如何,这里是如何获得积分,给定函数和积分边界。

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