Seaborn 热图颜色条自定义位置

Seaborn Heatmap Colorbar Custom Location

鉴于此热图:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)

我想将颜色条放置在自定义位置(根据 axis/plot 坐标)并具有自定义大小。 具体来说,我希望它水平位于左上角(热图之外),尺寸较小(但尚未定义)。这可能吗?我知道有一般的位置参数,但那些不允许我想做的事情。我也知道我可以用 plt.colorbar() 定义一个单独的颜色条,但我也不知道如何自定义它的位置。

提前致谢!

可以使用"inset axes" to create an ax for the colorbar that goes perfectly together with the subplot. In this tutorial example "cax" is the "ax" for the colorbar. In seaborn's heatmapcbar_ax是颜色条放置的位置(当cbar_ax没有给出时,matplotlib选择默认位置)。 cbar_kw 可以为颜色栏设置额外的关键字,例如设置水平方向。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()

uniform_data = np.random.rand(10, 12)
fig, ax = plt.subplots()
cax = inset_axes(ax,
                 width="40%",  # width: 40% of parent_bbox width
                 height="10%",  # height: 10% of parent_bbox height
                 loc='lower left',
                 bbox_to_anchor=(0, 1.1, 1, 1),
                 bbox_transform=ax.transAxes,
                 borderpad=0,
                 )
sns.heatmap(uniform_data, ax=ax, cbar_ax=cax, cbar_kws={'orientation': 'horizontal'} )
plt.subplots_adjust(top=0.8) # make room to fit the colorbar into the figure
plt.show()