密致布局指南
譯者:飛龍
協(xié)議:CC BY-NC-SA 4.0
tight_layout
會(huì)自動(dòng)調(diào)整子圖參數(shù)堪伍,使之填充整個(gè)圖像區(qū)域觅闽。這是個(gè)實(shí)驗(yàn)特性谱煤,可能在一些情況下不工作刘离。它僅僅檢查坐標(biāo)軸標(biāo)簽、刻度標(biāo)簽以及標(biāo)題的部分茧痕。
簡(jiǎn)單的示例
在 matplotlib 中恼除,軸域(包括子圖)的位置以標(biāo)準(zhǔn)化圖形坐標(biāo)指定。 可能發(fā)生的是舀患,你的軸標(biāo)簽或標(biāo)題(有時(shí)甚至是刻度標(biāo)簽)會(huì)超出圖形區(qū)域气破,因此被截?cái)唷?/p>
plt.rcParams['savefig.facecolor'] = "0.8"
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
為了避免它低匙,軸域的位置需要調(diào)整碳锈。對(duì)于子圖售碳,這可以通過(guò)調(diào)整子圖參數(shù)(移動(dòng)軸域的一條邊來(lái)給刻度標(biāo)簽騰地方)。Matplotlib v1.1 引入了一個(gè)新的命令tight_layout()
竿屹,自動(dòng)為你解決這個(gè)問(wèn)題。
plt.tight_layout()
當(dāng)你擁有多個(gè)子圖時(shí)力惯,你會(huì)經(jīng)痴偎唬看到不同軸域的標(biāo)簽疊在一起弄跌。
plt.close('all')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
tight_layout()
也會(huì)調(diào)整子圖之間的間隔來(lái)減少堆疊铛只。
tight_layout()
可以接受關(guān)鍵字參數(shù)pad
淳玩、w_pad
或者h_pad
蜕着,這些參數(shù)圖像邊界和子圖之間的額外邊距。邊距以字體大小單位規(guī)定蓖乘。
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
即使子圖大小不同驱敲,tight_layout()
也能夠工作,只要網(wǎng)格的規(guī)定的兼容的握牧。在下面的例子中沿腰,ax1
和ax2
是 2x2 網(wǎng)格的子圖狈定,但是ax3
是 1x2 網(wǎng)格纽什。
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()
它適用于使用subplot2grid()
創(chuàng)建的子圖芦缰。 一般來(lái)說(shuō)让蕾,從gridspec
(使用GridSpec
自定義子布局的位置)創(chuàng)建的子圖也能正常工作。
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
雖然沒(méi)有徹底測(cè)試,它看起來(lái)也適用于aspect
不為auto
的子圖(例如帶有圖像的軸域)顿颅。
arr = np.arange(100).reshape((10,10))
plt.close('all')
fig = plt.figure(figsize=(5,4))
ax = plt.subplot(111)
im = ax.imshow(arr, interpolation="none")
plt.tight_layout()
警告
-
tight_layout()
只考慮刻度標(biāo)簽庇配,軸標(biāo)簽和標(biāo)題栖疑。 因此遇革,其他藝術(shù)家可能被截?cái)嗖⑶乙部赡苤丿B揭糕。 - 它假定刻度標(biāo)簽著角,軸標(biāo)簽和標(biāo)題所需的額外空間與軸域的原始位置無(wú)關(guān)旋恼。 這通常是真的冰更,但在罕見(jiàn)的情況下不是。
-
pad = 0
將某些文本剪切幾個(gè)像素舟铜。 這可能是當(dāng)前算法的錯(cuò)誤或限制谆刨,并且不清楚為什么會(huì)發(fā)生归斤。 同時(shí)脏里,推薦使用至少大于 0.3 的間隔。
和GridSpec
一起使用
GridSpec
擁有自己的tight_layout()
方法(pyplot API 的tight_layout()
也能生效)鸦难。
plt.close('all')
fig = plt.figure()
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig)
你可以提供一個(gè)可選的rect
參數(shù),指定子圖所填充的邊框介返。 坐標(biāo)必須為標(biāo)準(zhǔn)化圖形坐標(biāo)圣蝎,默認(rèn)值為(0, 0, 1, 1)
衡瓶。
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
例如哮针,這可用于帶有多個(gè)gridspecs
的圖形。
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
我們可以嘗試匹配兩個(gè)網(wǎng)格的頂部和底部捂齐。
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
雖然這應(yīng)該足夠好了奠宜,調(diào)整頂部和底部可能也需要調(diào)整hspace
瞻想。 為了更新hspace
和vspace
蘑险,我們?cè)俅问褂酶潞蟮?code>rect參數(shù)調(diào)用tight_layout()
。 注意嘴高,rect
參數(shù)指定的區(qū)域包括刻度標(biāo)簽拴驮。因此柴信,我們將底部(正常情況下為 0)增加每個(gè)gridspec
的底部之差随常。 頂部也一樣。
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
0.5, 1 - (gs1.top-top)])
gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
None, 1 - (gs2.top-top)],
h_pad=0.5)
和AxesGrid1
一起使用
雖然受限但也支持axes_grid1
工具包
plt.close('all')
fig = plt.figure()
from mpl_toolkits.axes_grid1 import Grid
grid = Grid(fig, rect=111, nrows_ncols=(2,2),
axes_pad=0.25, label_mode='L',
)
for ax in grid:
example_plot(ax)
ax.title.set_visible(False)
plt.tight_layout()
顏色條
如果你使用colorbar
命令創(chuàng)建了顏色條枣察,創(chuàng)建的顏色條是Axes
而不是Subplot
的實(shí)例,所以tight_layout
沒(méi)有效果臂痕。在 Matplotlib v1.1 中握童,你可以使用gridspec
將顏色條創(chuàng)建為子圖叛赚。
plt.close('all')
arr = np.arange(100).reshape((10,10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
plt.colorbar(im, use_gridspec=True)
plt.tight_layout()
![])http://matplotlib.org/_images/tight_layout_guide-14.png
另一個(gè)選項(xiàng)是使用AxesGrid1
工具包,顯式為顏色條創(chuàng)建一個(gè)軸域:
plt.close('all')
arr = np.arange(100).reshape((10,10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)
plt.tight_layout()