备注
转到末尾 以下载完整示例代码。
使用 plt.subplots 创建多个子图#
pyplot.subplots 通过一次调用创建一个图形和一个子图网格,同时提供对单个图创建方式的合理控制。对于更高级的使用场景,您可以使用 GridSpec 进行更通用的子图布局,或使用 Figure.add_subplot 在图形的任意位置添加子图。
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
只有一个子图的图形#
subplots() 不带参数返回一个 Figure 和一个单独的 Axes。
这实际上是创建单个图形和轴的最简单且推荐的方法。
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('A single plot')

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

如果你只创建几个 Axes,立即将它们解包到每个 Axes 的专用变量会很方便。这样,我们可以使用 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 是一个二维的 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)
你也可以在二维中使用元组解包,将所有子图分配给专用变量:
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)。特别是,这可以用来创建一个极坐标轴的网格。
fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
ax1.plot(x, y)
ax2.plot(x, y ** 2)
plt.show()

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





