matplotlib 1.5.3&tight_layout()如何与subplots_adjust()交互?

时间:2017-11-10 07:42:05

标签: python matplotlib

我在Python 3中使用Matplotlib 1.5.3。我有一个3x3子图结构,或者更通常是一个未指定的子图结构,我试图添加一个颜色条。根据{{​​3}},一个明显好的方法是使用subplots_adjust()扭曲子图,并将颜色条添加为新轴。除此之外,我启用了tight_layout(),并且完全混淆了事物。根据我所读到的关于subplots_adjust()的内容,这个功能应该起作用:

import matplotlib.pyplot as plt

def add_colorbar(last_im):
    SPACE   = 0.2  # portion of final width reserved for colorbar and its padding
    PADDING = 0.5  # portion of reserved space reserved for padding
    fig = plt.gcf()

    # expand image to make room for colorbar
    w,h = fig.get_size_inches()
    fig.set_size_inches((w/(1-SPACE), h))

    # shrink right side of subplot to create empty space on
    # right hand side
    fig.subplots_adjust(right=0.9*(1-SPACE)) # 0.9 being the original value

    # create colorbar axes, place in empty space with padding
    cbax = fig.add_axes([1-SPACE*(1-PADDING/2), 0.15,
                         SPACE*(1-PADDING),     0.7])
    fig.colorbar(last_im, cax=cbax)

但是子图配置保持居中,因此基本上没有空间,并且颜色条直接绘制在子图上。我也尝试使用plt.tight_layout(rect=[0, 0, 1-SPACE, 1])代替subplots_adjust(),但这似乎比subplots_adjust()语句更低,并且基本上只是各个子图的大小混乱。似乎这些功能都不像我所宣传的那样起作用。我错过了什么?下图显示错误的情节,情节标题被审查为安全的一面。

this thread,

或者,我可以使用添加色条的解决方案,该色条通常适用于具有任何子图配置的图形,但我更喜欢理解subplots_adjust()的令人困惑的行为和tight_layout() rect。

编辑:问题最终导致我在运行tight_layout()后错误地拨打了add_colorbar()个电话。现在我已经删除了呼叫,因此观察到了正确的行为。

0 个答案:

没有答案
相关问题