【问题标题】:When using seaborn to draw heatmap, can I mark multiple rows as one label?使用seaborn绘制热图时,可以将多行标记为一个标签吗?
【发布时间】:2020-09-18 19:05:14
【问题描述】:

我正在绘制热图。我想用它的类别替换原来的 y 轴。例如: 数据:

                    Location 1    Location 2      Location 3
cluster 1:    0       0.3           0.5              0.7
cluster 1:    1       1.2           3.1              1.2
cluster 1:    2       0.8           0.1              1.3
cluster 2:    3       0.2           0.3              1.0
cluster 2:    4       3.1           2.1              5
cluster 3:    5       0.9           0.7              0.2

我不想显示索引(0,1,2,3,4,5),而是想显示多行的簇号。我该怎么做?

【问题讨论】:

    标签: python matplotlib seaborn heatmap


    【解决方案1】:

    您可以遍历标签并将它们定位在平均值处。次要的 y 刻度可以用作分隔符。

    以下代码假设第一列具有集群标签(并且不会用于热图本身)。

    import pandas as pd
    import seaborn as sns
    from io import StringIO
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FixedLocator
    
    data_str = '''    cluster                "Location 1"    "Location 2"      "Location 3"
    "cluster 1"         0.3           0.5              0.7
    "cluster 1"         1.2           3.1              1.2
    "cluster 1"         0.8           0.1              1.3
    "cluster 2"         0.2           0.3              1.0
    "cluster 2"         3.1           2.1              5
    "cluster 3"         0.9           0.7              0.2'''
    
    df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
    ax = sns.heatmap(df[df.columns[1:]], cmap='rocket_r', annot=True)
    
    ax.xaxis.tick_top()
    ticks = []
    labels = []
    prev_label = None
    for i, label in enumerate(df['cluster']):
        if label != prev_label:
            ticks.append(i)
            labels.append(label)
            prev_label = label
    ticks.append(i + 1)
    ax.yaxis.set_minor_locator(FixedLocator(ticks))
    ax.yaxis.set_major_locator(FixedLocator([(t0 + t1) / 2 for t0, t1 in zip(ticks[:-1], ticks[1:])]))
    ax.set_yticklabels(labels, rotation=0)
    ax.tick_params(axis='both', which='major', length=0)
    ax.tick_params(axis='y', which='minor', length=60)
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 1970-01-01
      • 2021-02-26
      • 2019-05-07
      • 2016-03-29
      • 2017-07-12
      • 2018-05-23
      • 2017-02-16
      • 2018-11-23
      相关资源
      最近更新 更多