【发布时间】:2017-03-29 09:47:04
【问题描述】:
默认情况下,Seaborn 热图中的注释位于每个单元格的中间。 是否可以将注释移动到“左上角”。
【问题讨论】:
标签: python matplotlib seaborn
默认情况下,Seaborn 热图中的注释位于每个单元格的中间。 是否可以将注释移动到“左上角”。
【问题讨论】:
标签: python matplotlib 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())
【讨论】:
~(-0.5,+0.5)。如果您同时使用否定 (~(-0.5,-0.5)),则注释将位于“左下角”,另外还有 "va": 'bottom',这不是问题所要求的。
您可以使用 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
【讨论】:
xticks和yticks的x,y位置。默认情况下,注释以刻度位置为中心。通过在annot_kws 中设置ha=left、va=top,您所做的只是设置相对于刻度位置的文本位置,不是相对于单元格的位置:注意注释现在位于它们的左侧和顶部现在与刻度标签的中心对齐。
1,但它显示27
x 和 y 时,您可以将标签放置在任何需要的位置,而不需要 ha 和 va 的值。
ha 和va。第二个图中的标签不与数据相对应。