【问题标题】:Grouping the tick marks for heatmaps在 Python 中对热图的刻度线进行分组
【发布时间】:2022-01-05 15:06:26
【问题描述】:

我有一个看起来像这样的热图(来自:Plotting a 2D heatmap with Matplotlib)。

我正在尝试创建一个热图,它没有每个值的刻度标签,而是按范围分组。例如,前三个刻度线未签名,但已与一个联合签名的“Apples”签名。

使用以下方法完全禁用刻度标签似乎很容易:

plt.tick_params(
    axis='x',
    which='both',
    bottom=False,
    top=False,
    labelbottom=False)

或仅选择选定的刻度:

for (i,l) in enumerate(ax.xaxis.get_ticklabels()):
    if i == 0 or i == 4 or i == 5:
        l.set_visible(True)
    else:
        l.set_visible(False) 

但是可以按照下面的方式完成吗?

热图示例代码:

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()

【问题讨论】:

    标签: python seaborn heatmap


    【解决方案1】:

    您可以使用 xaxis 变换来放置文本和绘制短线,使用数据坐标作为 x 位置,使用轴坐标作为 y 位置(底部为 0,顶部为 1)。默认情况下,文本不会被轴剪切,但其他元素会被剪切,因此它们需要 clip_on=False 才能在主绘图区域之外可见。

    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    
    corr = np.corrcoef(np.random.randn(10, 20))
    corr[np.triu_indices_from(corr)] = np.nan
    sns.set_style("white")
    ax = sns.heatmap(corr, vmax=.3, square=True, cmap="YlGnBu",
                     annot=True, fmt='.2f', cbar_kws={'pad': 0})
    labels = ['Apples', 'Oranges', 'Pears', 'Bananas']
    label_lens = [4, 2, 1, 3]
    
    ax.set_xticks([]) # remove the x ticks
    ax.set_yticks([]) # remove the y ticks
    pos = 0
    for label, label_len in zip(labels, label_lens):
        if pos != 0:
            ax.vlines(pos, pos, len(corr), color='r', lw=2)
            ax.vlines(pos, 0, -0.02, color='r', lw=2,
                      transform=ax.get_xaxis_transform(), clip_on=False)
            ax.hlines(pos, 0, pos, color='r', lw=2)
            ax.hlines(pos, 0, -0.02, color='r', lw=2,
                      transform=ax.get_yaxis_transform(), clip_on=False)
        ax.text(pos + label_len / 2, -0.02, label, ha='center', va='top',
                transform=ax.get_xaxis_transform())
        ax.text(-0.02, pos + label_len / 2, label, ha='right', va='center', rotation=90,
                transform=ax.get_yaxis_transform())
        pos += label_len
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • @Mr.T 确实如此。这只是 OP 示例的副本。也许是为了避免太多接近零的值得到相同的颜色。它在很大程度上取决于数据集和想要传达的信息。
    • 我只是想知道为什么颜色条以 0.3 结束,尽管存在高于该值的值。
    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2021-02-22
    • 2020-07-17
    • 2021-04-16
    • 2021-10-27
    • 2020-09-07
    • 2015-05-19
    相关资源
    最近更新 更多