matplotlibight_layout + gridspec + fig.suptitle看起来很糟糕

时间:2018-12-05 22:59:52

标签: python matplotlib

我使用Matplotlib 2.2.2有一个非常漂亮的GridSpec图,但是我不能为整个图打一个漂亮的标题。示例:

score_winter_summer

如果我在没有紧凑布局的情况下运行import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np %matplotlib inline def example(tl): fig = plt.figure(figsize=(14,8)) hr = [3,3,3,1,1] wr = [3,1] ny = len(hr) nx = len(wr) gs = gridspec.GridSpec(ny,nx, height_ratios=hr, width_ratios=wr, hspace=0.08, wspace=0.1) for j in xrange(nx): ax = [fig.add_subplot(gs[0,j])] ax += [fig.add_subplot(gs[i,j], sharex=ax[0]) for i in xrange(1,ny)] for axi in ax: axi.plot([0,1,2],[0,1,4]) fig.suptitle('The quick brown fox jumps over the lazy dog.') if tl: gs.tight_layout(fig) ,则会在图形上方获得大量空间:

enter image description here

如果我为紧凑的布局运行example(False),则会得到负数空格:

enter image description here

我该如何解决这个问题,并从子图中获得具有适当边距的图形级标题?

1 个答案:

答案 0 :(得分:2)

SELECT CNTRCT_ID , COALESCE( AMD_COUNT, 0 ) AS AMD_COUNT , AMD_DT_MIN FROM CONTRACTS LEFT JOIN ( SELECT REF_ID , MIN( AMEND_DT ) AS AMD_DT_MIN , COUNT( * ) AS AMD_COUNT FROM AMENDMENTS GROUP BY REF_ID ) G ON CONTRACTS.CNTRCT_ID = G.REF_ID 并未考虑图形艺术家。

使用constrained_layout

但是,有一个相对较新的替代方法,称为constrained_layout。使用此名称,将包括图形标题。请注意,要执行此操作,您需要通过其tight_layout()参数将数字提供给GridSpec

figure

enter image description here

更新上边距

或者,您可以在调用import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def example(tl): fig = plt.figure(figsize=(14,8), constrained_layout=tl) hr = [3,3,3,1,1] wr = [3,1] ny = len(hr) nx = len(wr) gs = gridspec.GridSpec(ny,nx, figure=fig, height_ratios=hr, width_ratios=wr, hspace=0.08, wspace=0.1) for j in range(nx): ax = [fig.add_subplot(gs[0,j])] ax += [fig.add_subplot(gs[i,j], sharex=ax[0]) for i in range(1,ny)] for axi in ax: axi.plot([0,1,2],[0,1,4]) fig.suptitle('The quick brown fox jumps over the lazy dog.') example(True) plt.show() 之后在 之后更新上边距。例如。

tight_layout

代码:

gs.update(top=0.95)

enter image description here