注意
转到末尾下载完整的示例代码。
使用 plt.subplots
创建多个子图#
pyplot.subplots
通过单个调用创建一个图形和子图网格,同时为如何创建各个绘图提供合理的控制。对于更高级的用例,您可以使用 GridSpec
获取更通用的子图布局,或使用 Figure.add_subplot
在图形内的任意位置添加子图。
只有一个子图的图形#
不带参数的 subplots()
返回一个 Figure
和一个 Axes
。
这实际上是创建单个图形和轴的最简单和推荐的方法。
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('A single plot')

在一个方向堆叠子图#
pyplot.subplots
的前两个可选参数定义子图网格的行数和列数。
仅在一个方向堆叠时,返回的 axs
是一个 1D numpy 数组,其中包含已创建轴的列表。
fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs[0].plot(x, y)
axs[1].plot(x, -y)

如果只创建几个轴,立即将它们解包到每个轴的专用变量会很方便。这样,我们可以使用 ax1
而不是更冗长的 axs[0]
。
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

要获得并排的子图,请传递参数 1, 2
表示一行和两列。
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

在两个方向堆叠子图#
在两个方向堆叠时,返回的 axs
是一个 2D NumPy 数组。
如果必须为每个子图设置参数,则使用 for ax in axs.flat:
迭代 2D 网格中的所有子图会很方便。
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')
for ax in axs.flat:
ax.set(xlabel='x-label', ylabel='y-label')
# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
ax.label_outer()
![Axis [0, 0], Axis [0, 1], Axis [1, 0], Axis [1, 1]](../../_images/sphx_glr_subplots_demo_005.png)
您也可以在 2D 中使用元组解包来将所有子图分配给专用变量
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y**2, 'tab:orange')
ax3.plot(x, -y, 'tab:green')
ax4.plot(x, -y**2, 'tab:red')
for ax in fig.get_axes():
ax.label_outer()

极坐标轴#
pyplot.subplots
的参数 subplot_kw 控制子图的属性(另请参阅 Figure.add_subplot
)。特别是,这可以用来创建一个极坐标轴网格。

脚本的总运行时间:(0 分钟 8.717 秒)