如何在`tight_layout()`之后保持恒定的间距? [英] How to keep constant spacing after `tight_layout()`?

查看:50
本文介绍了如何在`tight_layout()`之后保持恒定的间距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人能找到答案(或经验),因为谷歌搜索并没有太大帮助.

Hopefully someone has an answer (or experience) as Googling doesn't help much.

以下是格式化程序功能的一些示例代码:

Here's some example code of a formatter function:

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(),将颜色栏和颜色栏标题之间​​的间隔设置为固定宽度(我可以手动设置此宽度,但是如何?).我该怎么办?

The goal: have the space between the colorbar and the colorbar title be a fixed width, regardless of tight_layout() being used (I would be okay with manually setting this width, but how?). How can I do that?

推荐答案

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

This will allow you to set the position of the colorbar label anywhere you want using coordinates:

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 就是这种情况.

What you are basically doing is just putting text at a certain position. To my knowledge, this is the only way to set the position of any title/label. This will not be influenced by the tick width as is the case with labelpad.

结果如下:

这篇关于如何在`tight_layout()`之后保持恒定的间距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆