【问题标题】:How to keep constant spacing after `tight_layout()`?如何在“tight_layout()”之后保持恒定间距?
【发布时间】:2014-10-15 00:56:10
【问题描述】:

希望有人有答案(或经验),因为谷歌搜索没有太大帮助。

这是格式化程序函数的一些示例代码:

from matplotlib.ticker import FuncFormatter

def latex_float(f, pos=0):
    float_str = "{0:.2g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"${0} \times 10^{{{1}}}$".format(base, int(exponent))
    else:
        return r"${}$".format(float_str)

然后在后面的代码中

cbar = pl.colorbar(ticks=np.logspace(0, np.log10(np.max(hist)), 10), format=formatter)#'%.2e')
cbar.set_label('number density', fontsize=labelsize)
cbar.ax.tick_params(labelsize=labelsize-6)
pl.savefig('somefilename.png', bbox_inches='tight')

有时,它会产生类似的输出

有时它会产生类似的输出

目标:无论使用tight_layout(),让颜色条和颜色条标题之间的空间为固定宽度(我可以手动设置这个宽度,但如何?)。我该怎么做?

【问题讨论】:

  • @Emilien - 不。 Labelpad 将根据可用的最宽刻度推送标签,而不是从“轴”本身。请注意,tight_layout() 也在使用中,因此必须有一种方法可以始终如一地执行此操作。它也与问题无关,因为那里提到的内容不适用于tight_layout()

标签: python-2.7 matplotlib plot colorbar


【解决方案1】:

取自How do I adjust (offset) colorbar title in matplotlib,您可以使用手动设置颜色栏标题

cb = colorbar()
cb.set_ticks([0,255])
ax = cb.ax
ax.text(1.3,0.5,'Foo',rotation=90)

这样,您可以指定标题与颜色栏的 x 距离。 (在这种情况下,1.3 是 x 值。)您显然还需要根据需要设置“刻度”...

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这将允许您使用坐标在任何您想要的位置设置颜色条标签的位置:

    import numpy
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    #Init data
    data = numpy.random.random((10, 10))
    
    #Create plotting frame
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)
    
    #Plot data
    im = ax1.imshow(data)
    
    #Only required for the small spacing between figure and colorbar
    divider = make_axes_locatable(ax1)
    cax = divider.append_axes("right", size = "5%", pad = 0.05)
    
    #Set colorbar, including title and padding
    cbar = fig.colorbar(im, cax = cax)
    
    cbar_title = "number density"
    plt.text(1.2, .5, cbar_title,  fontsize=20, verticalalignment='center', rotation = 90, transform = ax1.transAxes)
    
    fig.tight_layout()
    

    您基本上所做的只是将文本放在某个位置。据我所知,这是设置任何标题/标签位置的唯一方法。这不会像labelpad 那样受tick width 的影响。

    结果如下:

    【讨论】: