如何设置长宽比 < 1 的图像的 Matplotlib 颜色条高度

Las*_*yer 5 python matplotlib colorbar

我正在尝试获取图像的颜色条,该颜色条应该与图像具有相同的高度。这里建议了很多解决方案,但没有一个适用于长宽比小于 1 的图像。

如果您使用链接问题中接受的答案,如下所示......

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)), aspect = 0.4375)

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)
plt.savefig("asdf.png", bbox_inches = "tight")
Run Code Online (Sandbox Code Playgroud)

...(注意 imshow 调用中的方面!),我得到这个:

在此输入图像描述

不考虑纵横比,它工作得很好,但对于我的数据,我需要设置纵横比,因为 x 轴的步长比 y 轴的步长大得多。

其他解决方案(例如plt.colorbar(im,fraction=0.046, pad=0.04)或添加单独的轴)也不起作用并产生类似的结果。

在这种情况下如何使颜色条具有相同的高度?

Las*_*yer 8

我终于在这里找到了解决方案:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

...

fig, ax = plt.subplots(1, 1)
im = ax.imshow(data, aspect = aspectRatio)
axins = inset_axes(ax, width = "5%", height = "100%", loc = 'lower left',
                   bbox_to_anchor = (1.02, 0., 1, 1), bbox_transform = ax.transAxes,
                   borderpad = 0)
fig.colorbar(im, cax = axins)
Run Code Online (Sandbox Code Playgroud)

...其中data是您的值数组,并且1.02是图形和颜色条之间的填充。

无论纵横比如何,这都会创建具有完美高度的颜色条。不要摆弄神奇的数字或任何类似的东西。