Matplotlib - Subplots() 函数
Matplotlib - 使用 subplots() 函数
Section titled “Matplotlib - 使用 subplots() 函数”matplotlib.pyplot.subplots() 函数是一个非常方便的工具,可以同时创建一个 Figure 和一组(以网格形式排列的)子图。在面向对象风格中,这是创建多个图的推荐方法。
fig, axes = plt.subplots(nrows=1, ncols=1, **kwargs)参数:
nrows,ncols:指定子图网格的行数和列数的整数。默认值为 1。sharex,sharey:布尔值或字符串(‘all’, ‘row’, ‘col’)。如果为True或'all',子图将共享相同的 x 轴或 y 轴(刻度、范围、比例)。'row'表示同一行内的子图共享坐标轴,'col'表示同一列内的子图共享坐标轴。这对于关联图非常有用。figsize:Figure 的尺寸元组(宽度, 高度),单位为英寸。subplot_kw:一个字典,其中包含传递给每个子图的add_subplot()调用的关键字参数(例如,{'projection': '3d'})。gridspec_kw:一个字典,其中包含传递给GridSpec构造函数的关键字参数(例如,{'hspace': 0.1, 'wspace': 0.1}),用于更精细地控制间距。- …以及其他 figure 关键字参数。
返回值:
fig:顶层matplotlib.figure.Figure对象。axes:一个Axes对象或一个Axes对象数组。 - 如果nrows=1且ncols=1,则axes是一个单独的Axes对象。 - 如果nrows > 1或ncols > 1,则axes是一个 NumPy 数组的Axes对象。你可以使用标准数组索引(例如,axes[0],axes[1, 2])访问单个 axes。
示例:创建一个 2x2 的网格并绘制不同的函数。
import matplotlib.pyplot as pltimport numpy as np
x = np.arange(1, 5)
# 创建一个 2x2 的子图网格# 共享同一行中图的 y 轴fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 7), sharey='row')
# --- 在每个 Axes 对象上绘图 ---
# 左上图 (axes[0, 0])axes[0, 0].plot(x, x*x, color='blue', marker='o')axes[0, 0].set_title('Square ($x^2$)')axes[0, 0].set_ylabel('Value') # 由于 sharey,只需在每行设置一次 Y 轴标签axes[0, 0].grid(True)
# 右上图 (axes[0, 1])axes[0, 1].plot(x, np.sqrt(x), color='red', marker='s')axes[0, 1].set_title('Square Root ($\sqrt{x}$)')axes[0, 1].grid(True)
# 左下图 (axes[1, 0])axes[1, 0].plot(x, np.exp(x), color='green', marker='^')axes[1, 0].set_title('Exponential ($e^x$)')axes[1, 0].set_xlabel('Input x') # 底部行的 X 轴标签axes[1, 0].set_ylabel('Value')axes[1, 0].grid(True)
# 右下图 (axes[1, 1])axes[1, 1].plot(x, np.log10(x), color='purple', marker='d')axes[1, 1].set_title('Logarithm ($\log_{10}(x)$)')axes[1, 1].set_xlabel('Input x')axes[1, 1].grid(True)
# --- 整体 Figure 调整 ---
# 为整个 Figure 添加一个居中标题fig.suptitle('Demonstrating plt.subplots()', fontsize=16)
# 调整布局以防止标题/标签重叠plt.tight_layout(rect=[0, 0, 1, 0.96]) # rect 用于调整以容纳 suptitle
plt.show()此示例演示了如何创建 2x2 的网格,使用数组表示法 (axes[row, col]) 访问每个 Axes,在每个 Axes 上绘制不同的数据,设置各自的标题,并使用共享坐标轴 (sharey='row'),以便同一行中的图形共享 y 轴的范围和刻度。使用 plt.tight_layout() 在处理多个子图时通常非常重要,以确保标签和标题不会重叠。