Matplotlib - Pyplot API
Matplotlib - Pyplot 接口
Section titled “Matplotlib - Pyplot 接口”matplotlib.pyplot 是一系列函数的集合,提供了 Matplotlib 库的状态机(state-based)接口。这意味着 pyplot 函数隐式地作用于“当前”的 Figure 和 Axes。其设计旨在让 MATLAB 用户感到熟悉。
每个 pyplot 函数都会对 Figure 进行一些更改:例如,创建一个 Figure,在 Figure 中创建一个绘图区域(Axes),在绘图区域中绘制一些线条,用标签(labels)装饰绘图等。
虽然对于简单的交互式绘图(例如在 Jupyter Notebook 中)很方便,但在更复杂的绘图或在可重用脚本和应用程序中,通常推荐使用面向对象 (OO) API。OO API 涉及显式创建和管理 Figure 和 Axes 对象。
常用 Pyplot 函数
Section titled “常用 Pyplot 函数”以下是一些常用 pyplot 函数的分类列表:
绘图函数 (Plotting Functions)
Section titled “绘图函数 (Plotting Functions)”| 函数 (Function) | 描述 (Description) |
|---|---|
plot() | 绘制 y 与 x 的关系图,可包含线条和/或标记。 |
scatter() | 创建 y 与 x 的散点图,可变标记大小和/或颜色。 |
bar() | 创建垂直柱状图。 |
barh() | 创建水平柱状图。 |
hist() | 绘制直方图。 |
boxplot() | 创建箱线图。 |
violinplot() | 创建小提琴图(结合箱线图和密度图)。 |
pie() | 绘制饼图。(谨慎使用,柱状图通常是更好的选择)。 |
imshow() | 将数据显示为图像;即在二维规则栅格上显示。 |
contour() / contourf() | 绘制等高线 / 绘制填充等高线。 |
quiver() | 绘制二维箭头场(矢量场)。 |
step() | 创建阶梯图。 |
fill_between() | 填充两条水平曲线之间的区域。 |
Figure 和 Axes 管理 (Figure and Axes Management)
Section titled “Figure 和 Axes 管理 (Figure and Axes Management)”| 函数 (Function) | 描述 (Description) |
|---|---|
figure() | 创建一个新的 Figure 或激活一个已存在的 Figure。 |
subplot() / subplots() | 向当前 Figure 添加一个子图 / 创建一个 Figure 和一组子图。 |
axes() | 向当前 Figure 添加一个 Axes。 |
gca() | 获取当前的 Axes 实例(instance)。 |
gcf() | 获取当前的 Figure 实例。 |
show() | 显示所有打开的 Figure。 |
savefig() | 将当前 Figure 保存到文件。 |
close() | 关闭一个 Figure 窗口。 |
clf() | 清除当前的 Figure。 |
cla() | 清除当前的 Axes。 |
绘图自定义 (Plot Customization)
Section titled “绘图自定义 (Plot Customization)”| 函数 (Function) | 描述 (Description) |
|---|---|
title() | 为当前的 Axes 设置标题。 |
xlabel() / ylabel() | 设置 x 轴 / y 轴的标签。 |
xlim() / ylim() | 获取或设置当前 Axes 的 x / y 轴范围。 |
xticks() / yticks() | 获取或设置 x 轴 / y 轴当前的刻度(tick)位置和标签。 |
legend() | 在当前的 Axes 上放置图例。 |
grid() | 配置网格线(grid lines)。 |
text() | 在 Axes 坐标内的任意位置添加文本。 |
annotate() | 为绘图添加注释(annotation)(文本和可选的箭头)。 |
请记住,使用 pyplot 会修改全局状态(global state)。调用 plt.plot() 后再调用 plt.title() 会隐式地将标题应用于 plt.plot() 操作所在的 Axes。
使用 Pyplot 的示例:
Section titled “使用 Pyplot 的示例:”import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)
plt.figure(figsize=(6, 4)) # 创建一个新的 figureplt.plot(x, y, label='sin(x)') # 在当前的 Axes 上绘制数据plt.title('简单的正弦波') # 为当前的 Axes 添加标题plt.xlabel('弧度') # 添加 x 轴标签plt.ylabel('值') # 添加 y 轴标签plt.legend() # 添加图例plt.grid(True) # 添加网格plt.show() # 显示 figure