Seaborn 热图注释在单元格中的位置

Position of Seaborn heatmap annotations in cells

默认情况下,Seaborn 热图中的注释在每个单元格的中间居中。 是否可以将注释移动到 "top left".

您可以使用 seaborn 的 annot_kws 并像这里一样设置垂直 (va) 和水平 (ha) 对齐(有时效果不好):

...
annot_kws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data, annot=True, annot_kws=annot_kws)
...

另一种手动放置标签的方法,如下所示:

import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

data = np.random.randint(100, size=(5,5))
ax = sns.heatmap(data)

# put labels manually
for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x, y+1, '%d' % data[data.shape[0] - y - 1, x],
         ha='left',va='top', color='r')
plt.show()

要了解更多信息并了解 matplotlib 中的文本布局(为什么第一个示例效果不好?),请阅读此主题:http://matplotlib.org/users/text_props.html

一个好主意可能是使用热图中的注释,这些注释由 annot=True 参数产生,然后将它们向上移动半个像素宽度,向左移动半个像素宽度。 为了使这个移动位置成为文本本身的左上角,hava 关键字参数需要设置为 annot_kws。 移位本身可以使用平移变换来完成。

import seaborn as sns
import numpy as np; np.random.seed(0)
import matplotlib.pylab as plt
import matplotlib.transforms

data = np.random.randint(100, size=(5,5))
akws = {"ha": 'left',"va": 'top'}
ax = sns.heatmap(data,  annot=True, annot_kws=akws)

for t in ax.texts:
    trans = t.get_transform()
    offs = matplotlib.transforms.ScaledTranslation(-0.48, 0.48,
                    matplotlib.transforms.IdentityTransform())
    t.set_transform( offs + trans )

plt.show()

该行为有点违反直觉,因为变换中的 +0.48 将标签向上移动(与轴的方向相反)。这种行为似乎在 seaborn 版本 0.8 中得到了纠正;对于 seaborn 0.8 或更高版本中的绘图,请使用更直观的变换

offs = matplotlib.transforms.ScaledTranslation(-0.48, -0.48,
                    matplotlib.transforms.IdentityTransform())