如何在`tight_layout()`之后保持恒定的间距?

时间:2014-08-21 11:45:01

标签: python-2.7 matplotlib plot colorbar

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

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

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^{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')
}$".format(base, int(exponent))
    else:
        return r"${}$".format(float_str)

然后在代码中

tight_layout()

有时,它会产生类似

的输出

enter image description here

有时会产生类似

的输出

enter image description here

目标 :无论使用{{1}}是什么,颜色栏和颜色条标题之间的空格都是固定的宽度(我会可以手动设置这个宽度,但是如何?)。我该怎么做?

2 个答案:

答案 0 :(得分:1)

这将允许您使用坐标设置颜色条标签的位置:

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()

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

结果如下:

enter image description here

答案 1 :(得分:0)

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值。)你显然需要根据你的需要设置'滴答'......

希望这有帮助。