【问题标题】:Position of Seaborn heatmap annotations in cellsSeaborn 热图注释在单元格中的位置
【发布时间】:2017-03-29 09:47:04
【问题描述】:

默认情况下,Seaborn 热图中的注释位于每个单元格的中间。 是否可以将注释移动到“左上角”。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    一个好主意可能是使用热图中的注释,这些注释由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())
    

    【讨论】:

    • 在我看来这是正确的答案……我会等几个小时再接受。你又一次完美地帮助了我。谢谢!
    • 为了获得显示的行为,我相信 ScaledTranslation 的前 2 个参数都应该是负数。
    • @NasaGeek 问题要求“左上角”。要获得它,您需要~(-0.5,+0.5)。如果您同时使用否定 (~(-0.5,-0.5)),则注释将位于“左下角”,另外还有 "va": 'bottom',这不是问题所要求的。
    • @ImportanceOfBeingErnest 然后我只能假设 matplotlib 或 seaborn 发生了一些变化。在 mpl 2.0.2 和 seaborn 0.8.0 上,您的确切代码将注释向下和向左移动到相邻的单元格中。
    • @NasaGeek 在 seaborn 更新到 0.8 的热图代码中一定发生了一些变化。我相应地更新了答案。感谢您指出这一点!
    【解决方案2】:

    您可以使用 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

    【讨论】:

    • 热图注解放置在xticksyticksx,y位置。默认情况下,注释以刻度位置为中心。通过在annot_kws 中设置ha=leftva=top,您所做的只是设置相对于刻度位置的文本位置,不是相对于单元格的位置:注意注释现在位于它们的左侧和顶部现在与刻度标签的中心对齐。
    • 完全正确。我专门添加了最后一个链接来澄清这种行为。
    • 另请注意,第二种方法中的标签不正确:由于 y 位置从上到下,但您的循环从下到上,标签垂直翻转。 (看(4,3)和(4,1)。两者中较轻的应该显示标签1,但它显示27
    • 是的,但是当您在循环中更改 xy 时,您可以将标签放置在任何需要的位置,而不需要 hava 的值。
    • 我现在不是在谈论hava。第二个图中的标签与数据相对应。
    猜你喜欢
    • 2020-11-28
    • 2021-12-05
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2020-06-21
    • 2020-04-19
    • 2017-10-31
    相关资源
    最近更新 更多