自定义注释Seaborn Heatmap

Tgs*_*591 15 python heatmap seaborn

我在Python中使用Seaborn来创建Heatmap.我能够使用传入的值来注释单元格,但是我想添加表示单元格意味着什么的注释.例如,0.000000我不想仅仅看到,而是希望看到相应的标签,例如"Foo"或0.000000 (Foo).

热图功能的Seaborn文档有点神秘,我相信参数是关键所在:

annot_kws : dict of key, value mappings, optional
  Keyword arguments for ax.text when annot is True.
Run Code Online (Sandbox Code Playgroud)

我尝试设置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)
Run Code Online (Sandbox Code Playgroud)

当我不使用annot_kws参数时,这是(工作)输出:

工作输出

在这里,当我在堆栈跟踪包括annot_kwsPARAM:

---------------------------------------------------------------------------
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
Run Code Online (Sandbox Code Playgroud)

最后,kws我在堆栈跟踪中传递的属性是字典,它看起来基本上是这样的:

kws = {'Foo': -0.231049060187, 'Bar': 0.0}
Run Code Online (Sandbox Code Playgroud)

希望一切都有意义,我很感激任何人都可以提供帮助.

ojy*_*ojy 35

最新版本的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 = '')
Run Code Online (Sandbox Code Playgroud)

注意,如果使用非数字标签,则必须使用fmt ='',因为默认值为fmt ='.2g',这仅对数值有意义,并且会导致文本标签出错. 在此输入图像描述

  • @SergioLucero 是否可以在此标签数组中添加浮点数?我收到错误消息 ValueError: Unknown format code 'g' for object of type 'numpy.str_' (3认同)

Ser*_*nov 7

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]);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


小智 6

我不相信在当前版本中这是可能的。如果您采用 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)
Run Code Online (Sandbox Code Playgroud)

请注意,您的文本标签的颜色可能有问题。在这里,我创建了一个自定义cmap,使所有标签都统一为黑色。