使用约束布局调整轴的大小#

Constrained layout 尝试调整图形中子图的大小,以确保 Axes 对象和 Axes 上的标签之间没有重叠。

更多详情请参见 约束布局指南 ,或参见 紧凑布局指南 作为替代方案。

import matplotlib.pyplot as plt


def example_plot(ax):
    ax.plot([1, 2])
    ax.set_xlabel('x-label', fontsize=12)
    ax.set_ylabel('y-label', fontsize=12)
    ax.set_title('Title', fontsize=14)

如果我们不使用 constrained layout,那么标签会与轴重叠。

fig, axs = plt.subplots(nrows=2, ncols=2, layout=None)

for ax in axs.flat:
    example_plot(ax)
Title, Title, Title, Title

添加 layout='constrained' 会自动调整。

fig, axs = plt.subplots(nrows=2, ncols=2, layout='constrained')

for ax in axs.flat:
    example_plot(ax)
Title, Title, Title, Title

下面是一个使用嵌套网格规格的更复杂示例。

fig = plt.figure(layout='constrained')

import matplotlib.gridspec as gridspec

gs0 = gridspec.GridSpec(1, 2, figure=fig)

gs1 = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=gs0[0])
for n in range(3):
    ax = fig.add_subplot(gs1[n])
    example_plot(ax)


gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[1])
for n in range(2):
    ax = fig.add_subplot(gs2[n])
    example_plot(ax)

plt.show()
Title, Title, Title, Title, Title

参考文献

以下示例展示了以下函数、方法、类和模块的使用:

由 Sphinx-Gallery 生成的图库