Matplotlib 简明教程

Matplotlib - Simple Plot

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

我们现在将使用 Matplotlib 显示一个简单的弧度角对正弦值的折线图。首先,按照惯例,使用别名 plt 导入 Matplotlib 包中的 Pyplot 模块。

import matplotlib.pyplot as plt

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

import numpy as np

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

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

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

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

Plot 查看器窗口由 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 笔记本与 Matplotlib 一起使用。

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

from matplotlib import pyplot as plt
import numpy as np

要在 notebook 本身中显示绘图输出(而不是在单独查看器中显示),输入以下魔法语句−

%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() 函数在 notebook 中生成正弦波显示(无需运行 show() 函数)−

plt.plot(x,y)

执行代码的最后一行后,将显示以下输出−

final line of code