mpl_gui.subplots#

mpl_gui.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)[源代码]#

创建一个图形和一组子图。

这个实用工具包装器使得在一个调用中方便地创建子图的常见布局,包括封闭的图形对象。

参数:
nrows, ncolsint, 默认值: 1

子图网格的行数/列数。

sharex, shareybool 或 {‘none’, ‘all’, ‘row’, ‘col’}, 默认值: False

控制 x (sharex) 或 y (sharey) 轴之间属性的共享

  • True 或 ‘all’: x 轴或 y 轴将在所有子图之间共享。

  • False 或 ‘none’: 每个子图的 x 轴或 y 轴将是独立的。

  • ‘row’: 每个子图的行将共享一个 x 轴或 y 轴。

  • ‘col’: 每个子图的列将共享一个 x 轴或 y 轴。

当子图沿列共享 x 轴时,仅创建底部子图的 x 刻度标签。类似地,当子图沿行共享 y 轴时,仅创建第一列子图的 y 刻度标签。要稍后打开其他子图的刻度标签,请使用 tick_params

当子图具有带单位的共享轴时,调用 set_units 将使用新单位更新每个轴。

squeezebool, 默认值: True
  • 如果为 True,则从返回的 Axes 数组中挤出额外的维度

    • 如果仅构造一个子图 (nrows=ncols=1),则将生成的单个 Axes 对象作为标量返回。

    • 对于 Nx1 或 1xM 子图,返回的对象是一个包含 Axes 对象的 1D numpy 对象数组。

    • 对于 NxM 子图,其中 N>1 且 M>1,则返回为 2D 数组。

  • 如果为 False,则完全不进行挤压:返回的 Axes 对象始终是包含 Axes 实例的 2D 数组,即使它最终变为 1x1。

subplot_kwdict, 可选

传递给 add_subplot 调用的关键字的字典,用于创建每个子图。

gridspec_kwdict, 可选

传递给 GridSpec 构造函数的关键字的字典,用于创建放置子图的网格。

**fig_kw

所有其他关键字参数都传递给 figure 调用。

返回:
figFigure
axAxes 或 Axes 数组

如果创建了多个子图,ax 可以是单个 Axes 对象或 Axes 对象数组。可以使用 squeeze 关键字控制生成的数组的维度,请参见上文。

处理返回值的典型习惯用法是

# using the variable ax for single a Axes
fig, ax = plt.subplots()

# using the variable axs for multiple Axes
fig, axs = plt.subplots(2, 2)

# using tuple unpacking for multiple Axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

名称 ax 和复数形式 axs 优先于 axes,因为对于后者,不清楚它是指单个 Axes 实例还是这些实例的集合。

示例

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Create four polar axes and access them through the returned array
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)