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

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

[<matplotlib.lines.Line2D object at 0x7f2d00efd510>]
如果您只创建几个 Axes,立即将它们解压缩到每个 Axes 的专用变量会很方便。这样,我们可以使用ax1
而不是更详细的axs[0]
.
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

[<matplotlib.lines.Line2D object at 0x7f2d00a95b70>]
要获得并排的子图,请传递一行和两列的参数。1, 2
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

[<matplotlib.lines.Line2D object at 0x7f2cfb43d330>]
在两个方向上堆叠子图#
在两个方向堆叠时,返回axs
的是一个 2D NumPy 数组。
如果您必须为每个子图设置参数,则可以方便地使用.for ax in axs.flat:
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()
![轴 [0, 0], 轴 [0, 1], 轴 [1, 0], 轴 [1, 1]](/stable/_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()

极轴#
参数subplot_kw控制pyplot.subplots
子图属性(另请参见Figure.add_subplot
)。特别是,这可用于创建极轴网格。

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