简体   繁体   English

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

[英]Position of Seaborn heatmap annotations in cells

The annotations in a Seaborn heatmap are centered in the middle of each cell by default. 默认情况下,Seaborn热图中的注释位于每个单元格的中间。 Is it possible to move the annotations to "top left". 是否可以将注释移到“左上方”。

A good idea may be to use the annotations from the heatmap, which are produces by the annot=True argument and later shift them half a pixel width upwards and half a pixel width left. 一个好主意可能是使用来自热图的注释,该注释由annot=True参数生成,然后将它们向上移动半个像素宽度,向左移动半个像素宽度。 In order for this shifted position to be the top left corner of the text itself, the ha and va keyword arguments need to set as annot_kws . 为了使此移位后的位置成为文本本身的左上角,必须将hava关键字参数设置为annot_kws The shift itself can be done using a translation transform. 移位本身可以使用平移变换来完成。

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

在此处输入图片说明

The behaviour is a bit counterintuitive as +0.48 in the transform shifts the label upwards (against the direction of the axes). 这种行为有点违反直觉,因为变换中的+0.48将标签向上移动(相对于轴的方向)。 This behaviour seems to be corrected in seaborn version 0.8; 在seaborn版本0.8中,此行为似乎已得到纠正。 for plots in seaborn 0.8 or higher use the more intuitive transform 对于Seaborn 0.8或更高版本的地块,使用更直观的变换

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

You can use annot_kws of seaborn and set vertical (va) and horizontal (ha) alignments like here (sometimes it works bad): 您可以使用annot_kws的annot_kws并在此处设置垂直(va)和水平(ha)对齐方式(有时效果不佳):

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

在此处输入图片说明

Another way put labels manually like here: 另一种方法是像下面这样手动放置标签:

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

在此处输入图片说明

For more information and to understand text layout (why 1st example works bad?) in matplotlib read this topic: http://matplotlib.org/users/text_props.html 有关更多信息并了解matplotlib中的文本布局(为什么第一个示例不好?),请阅读以下主题: http : //matplotlib.org/users/text_props.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM