如何在matplotlib中遮蔽曲线下的区域

luk*_*ell 28 python numpy matplotlib

我想用matplotlib来说明两个区域之间的定积分:x_0和x_1.

如何在给定下图的情况下,将matplotlib中曲线下的区域从x = -1阴影到x = 1

import numpy as np
from matplotlib import pyplot as plt
def f(t):
    return t * t

t = np.arange(-4,4,1/40.)
plt.plot(t,f(t))
Run Code Online (Sandbox Code Playgroud)

luk*_*ell 19

我想出的最终答案是使用fill_between.

我认为类型方法之间会有一个简单的阴影,但这正是我想要的.

section = np.arange(-1, 1, 1/20.)
plt.fill_between(section,f(section))
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,这是非常合适的方法。 (2认同)

gsp*_*spr 16

退房fill.这是填充约束区域的示例.


Clé*_*oud 14

如前所述,您应该使用fill_betweenpyplot 中的函数。

为了填充曲线下所需的区域,我建议使用where提供适合您的数据的过滤器的参数

import numpy as np
from matplotlib import pyplot as plt

def f(t):
    return t * t

t = np.arange(-4,4,1/40)

#Print the curve
plt.plot(t,f(t))

#Fill under the curve
plt.fill_between(
        x= t, 
        y1= f(t), 
        where= (-1 < t)&(t < 1),
        color= "b",
        alpha= 0.2)
        
plt.show()
Run Code Online (Sandbox Code Playgroud)

where参数接受一个 boolean 数组。因此,您可以在布尔值上使用 numpy 数组运算来简化操作。正如您在示例中看到的,我只是使用了 : (-1 < t)&(t < 1)。有关布尔数组的更多详细信息,请参见:http://www.math.buffalo.edu/~badzioch/MTH337/PT/PT-boolean_numpy_arrays/PT-boolean_numpy_arrays.html

您可以调整参数alpha(不透明度)并color使其看起来更好。这是期望的结果:

在此输入图像描述

文档fill_between可在此处找到: https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.fill_ Between.html