调整具有受限布局的坐标轴#

受限布局尝试调整图中的子图大小,以使坐标轴对象和坐标轴上的标签之间没有重叠。

有关更多详细信息,请参阅受限布局指南,并参阅紧凑布局指南以获取替代方案。

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)

如果我们不使用受限布局,则标签会与坐标轴重叠

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

下面是使用嵌套gridspecs的更复杂示例。

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

参考

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

标签: 组件:坐标轴 组件:子图 样式:尺寸 级别:初学者

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

由 Sphinx-Gallery 生成的画廊