自定义注释 Seaborn 热图

Custom Annotation Seaborn Heatmap

我在 Python 中使用 Seaborn 创建热图。我可以用传入的值对单元格进行注释,但我想添加注释来表示单元格的含义。例如,我不想只看到 0.000000,而是想看到相应的标签,例如 "Foo," 或 0.000000 (Foo).

热图函数的 Seaborn documentation 有点含糊不清,我认为这里的参数是关键:

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 参数时的(工作)输出:

这里是我 do 包含 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 中的

aanot_kws 有不同的用途,即它提供对 how 注释显示的访问,而不是 what 显示

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

我不认为这在当前版本中是可能的。如果您想要一个 hack-y 解决方法,您可以执行以下操作...

# 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 以使所有标签都统一为黑色。

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

这是一个例子

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',这仅对数值有意义,并且会导致文本标签出错。