Matplotlib - 简单绘图



在本章中,我们将学习如何使用 Matplotlib 创建一个简单的绘图。

现在我们将使用 Matplotlib 显示一个简单的线形图,该图显示弧度角与其正弦值的关系。首先,根据约定,我们从 Matplotlib 包中导入 Pyplot 模块,并使用别名 plt。

import matplotlib.pyplot as plt

接下来,我们需要一个要绘制的数字数组。NumPy 库中定义了各种数组函数,该库使用别名 np 导入。

import numpy as np

现在,我们使用 NumPy 库中的 arange() 函数获取 0 到 2π 之间角度的 ndarray 对象。

x = np.arange(0, math.pi*2, 0.05)

ndarray 对象用作图形的 x 轴上的值。对应于 x 中角度的正弦值将显示在 y 轴上,通过以下语句获取:-

y = np.sin(x)

使用 plot() 函数绘制来自两个数组的值。

plt.plot(x,y)

您可以设置绘图标题以及 x 和 y 轴的标签。

You can set the plot title, and labels for x and y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

通过 show() 函数调用绘图查看器窗口:-

plt.show()

完整的程序如下:-

from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

执行上述代码行时,将显示以下图形:-

Simple Plot

现在,在 Jupyter notebook 中使用 Matplotlib。

如前所述,从 Anaconda navigator 或命令行启动 Jupyter notebook。在输入单元格中,输入 Pyplot 和 NumPy 的导入语句:-

from matplotlib import pyplot as plt
import numpy as np

为了在笔记本本身(而不是在单独的查看器中)显示绘图输出,请输入以下魔法语句:-

%matplotlib inline

获取 x 作为包含 0 到 2π 之间弧度角的 ndarray 对象,以及每个角度的正弦值 y:-

import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

设置 x 和 y 轴的标签以及绘图标题:-

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

最后,执行 plot() 函数以在笔记本中生成正弦波显示(无需运行 show() 函数):-

plt.plot(x,y)

执行最后一行代码后,将显示以下输出:-

Final Line of Code
广告

© . All rights reserved.