Skip to content

Matplotlib - Axes 类

matplotlib.axes.Axes 类可以说是 Matplotlib 面向对象 API 中最核心和最重要的类。一个 Axes 对象表示一个 Figure 中的单个图或子图。它是数据被绘制的区域,包含 x 轴、y 轴(对于 3D 图包含 z 轴)、刻度、标签、标题以及绘制的数据本身(线条、标记、补丁等)。

你可以将 Figure 想象成画布,而 Axes 则是画布上实际绘制图形的单个画框(或多个画框)。

一个 Figure 可以包含多个 Axes 对象(例如,在子图中),但一个 Axes 对象只属于一个 Figure。

通常通过以下方式之一获取 Axes 对象:

  • 使用 plt.subplots()(推荐): 这是创建 Figure 和一个或多个按网格排列的 Axes 的最常见方式。
  • 使用 fig.add_subplot(): 在指定的网格位置向 Figure 添加一个 Axes。
  • 使用 fig.add_axes(): 在 Figure 中由 Figure 坐标 [left, bottom, width, height] 定义的精确位置添加一个 Axes。适用于自定义布局和嵌套图(inset plots)。
import matplotlib.pyplot as plt
# 方法 1: plt.subplots()
fig1, ax1 = plt.subplots() # 单个 Axes
fig2, axes = plt.subplots(2, 2) # 2x2 的 Axes 网格 (axes 是一个二维 NumPy 数组)
ax_top_left = axes[0, 0]
# 方法 2: fig.add_subplot()
fig3 = plt.figure()
ax3 = fig3.add_subplot(1, 1, 1)
# 方法 3: fig.add_axes()
fig4 = plt.figure()
ax4 = fig4.add_axes([0.1, 0.1, 0.8, 0.8]) # 主 Axes
ax_inset = fig4.add_axes([0.6, 0.6, 0.25, 0.25]) # 嵌套 Axes

一旦你有了 Axes 对象(例如,ax),就可以使用它的方法来创建和自定义你的图表。你可能从 pyplot 中熟悉的许多绘图函数(如 plt.plot())在 Axes 对象上都有对应的方法(如 ax.plot())。

  • ax.plot():绘制线条和标记图。
  • ax.scatter():散点图。
  • ax.bar() / ax.barh():柱状图(垂直/水平)。
  • ax.hist():直方图。
  • ax.boxplot() / ax.violinplot():箱线图/小提琴图。
  • ax.imshow():显示图像/数组。
  • ax.contour() / ax.contourf():等高线图。
  • 还有更多…
  • ax.set_title():设置图表标题。
  • ax.set_xlabel() / ax.set_ylabel():设置轴标签。
  • ax.set_xlim() / ax.set_ylim():设置轴限制。
  • ax.set_xticks() / ax.set_yticks():设置刻度位置。
  • ax.set_xticklabels() / ax.set_yticklabels():设置刻度标签。
  • ax.legend():添加图例。
  • ax.grid():配置网格线。
  • ax.text() / ax.annotate():添加文本/注释。
  • ax.set_xscale() / ax.set_yscale():设置轴比例(例如,‘linear’,‘log’)。
import matplotlib.pyplot as plt
import numpy as np
# 数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 使用 subplots() 创建 Figure 和 Axes
fig, ax = plt.subplots(figsize=(8, 5))
# 使用 Axes 方法绘制数据
line1 = ax.plot(x, y1, 'r-', label='Sine Wave', linewidth=2)
line2 = ax.plot(x, y2, 'b--', label='Cosine Wave', linewidth=2)
# 使用 Axes 方法自定义
ax.set_title('Sine and Cosine Waves', fontsize=16)
ax.set_xlabel('X Value', fontsize=12)
ax.set_ylabel('Y Value', fontsize=12)
ax.set_xlim(0, 10)
ax.set_ylim(-1.2, 1.2)
ax.grid(True, linestyle=':', alpha=0.7)
# 添加图例 - 自动使用 plot() 中的标签
ax.legend(loc='upper right', fontsize=10)
# 添加注释
ax.annotate('Intersection', xy=(np.pi/4, np.sin(np.pi/4)),
xytext=(2, 0.5),
arrowprops=dict(facecolor='black', shrink=0.05, width=1))
plt.tight_layout()
plt.show()

此示例明确创建了一个 Figure 和一个 Axes (fig, ax = plt.subplots())。所有后续的绘图 (ax.plot) 和自定义 (ax.set_title, ax.set_xlabel, ax.legend 等) 都是通过直接调用 ax 对象的方法来完成的。这种面向对象的方法使得代码更清晰、更易维护、更灵活,尤其是在处理复杂的图形时。