默认情况下,Seaborn热图中的注释位于每个单元格的中间。 是否可以将注释移到“左上角”。
答案 0 :(得分:4)
一个好主意可能是使用热图中的注释,这些注释由annot=True
参数产生,然后将它们向上移动半个像素宽度并向左移动半个像素宽度。
为了使此移位位置成为文本本身的左上角,ha
和va
关键字参数需要设置为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())
答案 1 :(得分:1)
您可以使用annot_kws
seaborn并设置此处的垂直(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