如何绘制给定集成的区域?

时间:2014-12-08 15:10:49

标签: python function matplotlib

我有以下脚本:

import numpy as np

def f(x):
    return x**2 + 3

def integration(a, b, n):
    dx = (b - a) / n
    integration = 0
    for i in np.arange(1, n + 1):
        integration += f(a + i * dx)
    integration *= dx
    return integration 

print(integration (0, 5, 10000))

现在,我想在f(x)a所描述的范围内绘制b的曲线,其下方有积分区域,所以我可以得到这样的结果:

enter image description here

我知道如何做第一部分,即在特定范围内绘制f(x)曲线:

import matplotlib.pylab as pl

x = np.linspace(0, 5, 10000)

def f(x):
    return x**2 + 3

pl.plot(x, f(x))
pl.xlim([-1, 6])
pl.show()

......但我没有休息。我很感激你的帮助。

2 个答案:

答案 0 :(得分:2)

感谢@Evert评论,这是一个有效的解决方案:

'''
According to the rectangle rule.
'''
import numpy as np
import matplotlib.pylab as pl
from matplotlib.patches import Polygon

# Function definition.
def f(x):
    return x ** 2 + 3

# Integration calculation.
def integration(a, b, n):
    dx = (b - a) / n
    integration = 0
    for i in np.arange(1, n + 1):
        integration += f(a + i * dx)
    integration *= dx
    return integration

# Define integral limits.
a, b = 0, 5

# Define x and y arrays.
x = np.linspace(0, 10, 10000)
y = f(x)

# Plot x and y.
fig, ax = pl.subplots()
pl.plot(x, y, 'b', linewidth = 2)
pl.xlim(xmin = -1, xmax = 11)
pl.ylim(ymin = 0)

# Shade area of the integration beneath the f(x) curve.
ix = np.linspace(a, b, 10000)
iy = f(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor = '0.9', edgecolor = '0.5')
ax.add_patch(poly)

# Print equation text.
pl.text(0.5 * (a + b), 60, r"$\int_{a}^{b}f(x)dx=%.2f$" %integration(a, b, 10000),
horizontalalignment = 'center', fontsize = 20)

# Add x and y axes labels.
pl.figtext(0.9, 0.05, '$x$')
pl.figtext(0.1, 0.9, '$y$')

# Remove right and top plot delimeter lines.
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')

# Add a and b ticks on x axis.
ax.set_xticks((a, b))
ax.set_xticklabels(('$a=%d$' %a, '$b=%d$' %b))
ax.set_yticks([])

# Show the plot.
pl.show()

enter image description here

答案 1 :(得分:0)

首先,考虑将变量integration重命名为intresult或其他内容。函数名和变量名之间可能会混淆。

至于手头的问题,您可以在同一组轴上多次使用pl.plot功能来创建额外的线条。因此,您可以使用以下代码绘制两条垂直线(图中粗黑线所代表的线):

pl.plot([a,a], [0,f(a)], "k-")
pl.plot([b,b], [0,f(b)], "k-")

在此代码中,"k-"表示绘图应为黑色(k)行(-)。这是matplotlib.pyplot中的一项功能,因此我不确定它是否适用于matplotlib.pylab

同样,可以使用pl.plot([a], [f(a)], "r.")等调用创建红点。同样,这适用于pyplot,但也适用于pylab

至于该地区,我不知道任何专用的区域填充功能。但是,您可以尝试使用多个蓝色垂直线对区域进行线条着色,重复调用pl.plot([x,x], [0,f(x)], "b-")以获取x的不同值。这是一个混乱的解决方案,但你可以试试。

尝试使用不同的功能,如果我的任何解决方案无效,请考虑尝试pyplot而不是pylab