Custom Annotation Seaborn Heatmap

前端 未结 3 971
醉梦人生
醉梦人生 2020-12-01 09:30

I\'m using Seaborn in Python to create a Heatmap. I\'m able to annotate the cells with the values passed in, but I\'d like to add annotations that signify what the cell mean

相关标签:
3条回答
  • 2020-12-01 10:04

    aanot_kws in Seaborn serves a different purpose, namely, it provides access to how annotations are displayed, rather than what is displayed

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    sns.set()
    fig, ax = plt.subplots(1,2)
    ata = np.array([[0.000000,0.000000],[-0.231049,0.000000],[-0.231049,0.000000]])
    sns.heatmap(data, vmin=-0.231049, vmax=0, annot=True, fmt='f', annot_kws={"size": 15}, ax=ax[0])
    sns.heatmap(data, vmin=-0.231049, vmax=0, annot=True, fmt='f', annot_kws={"size": 10}, ax=ax[1]);
    

    0 讨论(0)
  • 2020-12-01 10:16

    I don't believe this is possible in the current version. If you are up to a hack-y workaround, you could do the following ...

    # Create the 1st heatmap without labels 
    sns.heatmap(data=df1, annot=False,)
    
    # create the second heatmap, which contains the labels,
    # turn the annotation on,
    # and make it transparent
    sns.heatmap(data=df2, annot=True, alpha=0.0)
    

    Note that you may have a problem with the coloring of your text labels. Here, I created a custom cmap to have all labels uniformly black.

    0 讨论(0)
  • 2020-12-01 10:23

    This feature has just been added in the recent version of Seaborn 0.7.1.

    From Seaborn update history:

    The annot parameter of heatmap() now accepts a rectangular dataset in addition to a boolean value. If a dataset is passed, its values will be used for the annotations, while the main dataset will be used for the heatmap cell colors

    Here is an example

    data = np.array([[0.000000,0.000000],[-0.231049,0.000000],[-0.231049,0.000000]])
    labels =  np.array([['A','B'],['C','D'],['E','F']])
    fig, ax = plt.subplots()
    ax = sns.heatmap(data, annot = labels, fmt = '')
    

    Note, fmt = '' is necessary if you are using non-numeric labels, since the default value is fmt='.2g' which makes sense only for numeric values and would lead to an error for text labels.

    0 讨论(0)
提交回复
热议问题