簡體   English   中英

自定義注釋 Seaborn 熱圖

[英]Custom Annotation Seaborn Heatmap

我在 Python 中使用 Seaborn 創建熱圖。 我可以用傳入的值對單元格進行注釋,但我想添加注釋來表示單元格的含義。 例如,我不僅希望看到0.000000 ,還希望看到相應的 label,例如“Foo”或0.000000 (Foo)

熱圖 function 的Seaborn 文檔有點含糊不清,我認為參數是這里的關鍵:

annot_kws : dict of key, value mappings, optional
  Keyword arguments for ax.text when annot is True.

我嘗試將annot_kws設置為值別名的字典,即{'Foo': -0.231049060187, 'Bar': 0.000000}等,但我收到了 AttributeError。

這是我的代碼(為了可重現性,我在這里手動創建了數據數組):

data = np.array([[0.000000,0.000000],[-0.231049,0.000000],[-0.231049,0.000000]])
axs = sns.heatmap(data, vmin=-0.231049, vmax=0, annot=True, fmt='f', linewidths=0.25)

當我不使用annot_kws參數時,這是(工作)output:

工作輸出

這里是包含annot_kws參數時的堆棧跟蹤:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-57-38f91f1bb4b8> in <module>()
     12 
     13 
---> 14 axs = sns.heatmap(data, vmin=min(uv), vmax=max(uv), annot=True, annot_kws=kws, linewidths=0.25)
     15 concepts

/opt/anaconda/2.3.0/lib/python2.7/site-packages/seaborn/matrix.pyc in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, ax, xticklabels, yticklabels, mask, **kwargs)
    272     if square:
    273         ax.set_aspect("equal")
--> 274     plotter.plot(ax, cbar_ax, kwargs)
    275     return ax
    276 

/opt/anaconda/2.3.0/lib/python2.7/site-packages/seaborn/matrix.pyc in plot(self, ax, cax, kws)
    170         # Annotate the cells with the formatted values
    171         if self.annot:
--> 172             self._annotate_heatmap(ax, mesh)
    173 
    174         # Possibly add a colorbar

/opt/anaconda/2.3.0/lib/python2.7/site-packages/seaborn/matrix.pyc in _annotate_heatmap(self, ax, mesh)
    138             val = ("{:" + self.fmt + "}").format(val)
    139             ax.text(x, y, val, color=text_color,
--> 140                     ha="center", va="center", **self.annot_kws)
    141 
    142     def plot(self, ax, cax, kws):

/opt/anaconda/2.3.0/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in text(self, x, y, s, fontdict, withdash, **kwargs)
    590         if fontdict is not None:
    591             t.update(fontdict)
--> 592         t.update(kwargs)
    593         self.texts.append(t)
    594         t._remove_method = lambda h: self.texts.remove(h)

/opt/anaconda/2.3.0/lib/python2.7/site-packages/matplotlib/artist.pyc in update(self, props)
    755             func = getattr(self, 'set_' + k, None)
    756             if func is None or not six.callable(func):
--> 757                 raise AttributeError('Unknown property %s' % k)
    758             func(v)
    759             changed = True

AttributeError: Unknown property tokenized

最后, kws ,我在堆棧跟蹤行中傳遞的屬性,是字典,它看起來基本上是這樣的:

kws = {'Foo': -0.231049060187, 'Bar': 0.0}

希望一切都有意義,我將不勝感激任何人可以提供的幫助。

Seaborn 0.7.1的最新版本中剛剛添加了此功能。

Seaborn更新歷史記錄

現在,heatmap()的annot參數除了布爾值外,還接受矩形數據集。 如果傳遞了數據集,則其值將用於注釋,而主數據集將用於熱圖單元格顏色

這是一個例子

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 = '')

請注意,如果您使用的是非數字標簽,則必須使用fmt ='',因為默認值是fmt ='。2g',這僅對數值有意義,並且會導致文本標簽錯誤。 在此處輸入圖片說明

aanot_kws在Seaborn用於不同的用途,即,它提供了訪問是如何顯示的注釋,而不是所顯示的內容

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]);

在此處輸入圖片說明

我認為在當前版本中這是不可能的。 如果您可以解決問題,則可以執行以下操作...

# 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)

請注意,您的文本標簽的顏色可能有問題。 在這里,我創建了一個自定義cmap以使所有標簽統一為黑色。

這是 Python 中新的 python package 到 plot 復雜熱圖: https://github.com/DingWB/PyComplexHeatmap 使用這個 package,您可以添加不同類型的注釋(包括箱線圖、散點圖、條形圖)。

PyComplex 熱圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM