【问题标题】:How to plot the area of given integration?如何绘制给定积分的区域?
【发布时间】:2014-12-08 15:10:48
【问题描述】:

我有以下脚本:

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

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

我知道如何做第一部分,即在特定范围内绘制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()

...但我缺乏其余的。我将不胜感激。

【问题讨论】:

标签: python function matplotlib


【解决方案1】:

感谢@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()

【讨论】:

    【解决方案2】:

    首先,考虑将变量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

    【讨论】:

    • 对于竖线我觉得axvline是更好的选择。
    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    相关资源
    最近更新 更多