使用限制性配置調整軸大小#

限制性配置會嘗試調整圖表中的子圖大小,使軸物件和軸上的標籤之間沒有重疊。

請參閱限制性配置指南以取得更多詳細資料,並參閱緊密配置指南以取得替代方案。

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

以下是使用巢狀 gridspec 的更複雜範例。

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 分鐘 5.127 秒)

由 Sphinx-Gallery 產生圖庫