matplotlib strict_layout + gridspec + Fig.suptitle 看起来很糟糕

Jas*_*n S 4 python matplotlib

我使用 Matplotlib 2.2.2 有一个非常漂亮的 GridSpec 图,但我无法为整个图制作一个漂亮的标题。例子:

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)
Run Code Online (Sandbox Code Playgroud)

如果我运行example(False)的布局不紧凑,我会在数字上方获得大量空间:

在此输入图像描述

如果我追求example(True)紧凑的布局,我会得到负空间:

在此输入图像描述

我怎样才能解决这个问题并从子图中获得一个具有适当边距的图形级标题?

Imp*_*est 7

tight_layout()不考虑人物级别的艺术家。

使用constrained_layout

然而,有一个相对较新的替代方案,称为constrained_layout. 使用此功能,将包含图形标题。请注意,要使其工作,您需要将数字提供给GridSpecvia 它的figure参数。

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新上边距

或者,您可以在调用后更新上边距tight_layout。例如作为

gs.update(top=0.95)
Run Code Online (Sandbox Code Playgroud)

代码:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

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, 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.')
    if tl:
        gs.tight_layout(fig)
        gs.update(top=0.95)


example(True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述