zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python 教程之如何使用 matplotlib 在 python 中绘制数学函数

Pythonmatplotlib教程 如何 函数 绘制 数学 使用
2023-09-11 14:18:32 时间

在本教程中,我们将看到如何使用 matplotlib 绘制数学函数。
首先我们需要安装 matplotlib:

$ pip install matplotlib

现在让我们创建一个“start.py”文件并对其进行编辑。

我们将导入我们需要的库。Matplotlib来绘制我们的函数和numpy来创建我们的函数定义的值数组。

#import libraries
import matplotlib.pyplot as plt
import numpy as np

我们将需要一个 numpy 函数,它将在两点之间创建一个列表 n 值。这个函数叫做“ linspace ”
然后我们将使用 numpy 能力对数组进行计算。例如,如果你想跟踪 sin 函数,你可以使用np.sin(x)和 x 作为我们的值列表。

# define the border of the plot
x = np.linspace(-5, 5, 100) # my plot will be going from -5 to 5 and will have a rezolution of 100
# make the function
y = np.sin(x) # the function that I want to plot in function of x

我们完成了!!!
要显示绘图,我们只需要这两行如何将我们的函数添加到绘图并显示它。
注意:如果您只显示一个函数,则标签值没有用处。

# plot the function

plt.plot(x, y, color="red", label="f(x) = sin(x)") # plot the function
plt