[英]Position of Seaborn heatmap annotations in cells
默认情况下,Seaborn热图中的注释位于每个单元格的中间。 是否可以将注释移到“左上方”。
一个好主意可能是使用来自热图的注释,该注释由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())
您可以使用annot_kws
的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.