簡體   English   中英

在tight_layout之后調整matplotlib子圖間距

[英]adjust matplotlib subplot spacing after tight_layout

我想盡量減少圖中的空白。 我有一排子圖,其中四個圖共享其y軸,最后一個圖具有單獨的軸。 共享軸中間面板沒有ylabel或ticklabel。

tight_layout在中間圖之間創建了很多空白,好像為刻度標簽和ylabel留了空間,但是我寧願拉伸子圖。 這可能嗎?

import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure()
gs = gridspec.GridSpec(1, 5, width_ratios=[4,1,4,1,2]) 

ax = fig.add_subplot(gs[0])
axes = [ax] + [fig.add_subplot(gs[i], sharey=ax) for i in range(1, 4)]

axes[0].plot(np.random.randint(0,100,100))
barlist=axes[1].bar([1,2],[1,20])

axes[2].plot(np.random.randint(0,100,100))
barlist=axes[3].bar([1,2],[1,20])

axes[0].set_ylabel('data')

axes.append(fig.add_subplot(gs[4]))
axes[4].plot(np.random.randint(0,5,100))
axes[4].set_ylabel('other data')


for ax in axes[1:4]:
    plt.setp(ax.get_yticklabels(), visible=False)


sns.despine();
plt.tight_layout(pad=0, w_pad=0, h_pad=0);

在此處輸入圖片說明

w_pad = 0設置w_pad = 0不會更改tight_layout的默認設置。 您需要設置類似w_pad = -2 產生下圖:

在此處輸入圖片說明

您可以走得更遠,說-3但隨后您將開始與上一個情節有一些重疊。

另一種方法是刪除plt.tight_layout()並使用自己設置邊界

plt.subplots_adjust(left=0.065, right=0.97, top=0.96, bottom=0.065, wspace=0.14)

盡管這可能是一個反復試驗的過程。

編輯

通過將刻度線和最后一個圖的標簽移到右側,可以獲得漂亮的圖形。 答案表明您可以使用以下方法完成此操作:

ax.yaxis.tick_right()
ax.yaxis.set_label_position("right") 

因此,對於您的示例:

axes[4].yaxis.tick_right()
axes[4].yaxis.set_label_position("right")

另外,您需要刪除sns.despine() 最后,現在無需設置w_pad = -2 ,只需使用plt.tight_layout(pad=0, w_pad=0, h_pad=0)

使用此創建下圖:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM