自定义注释Seaborn Heatmap

时间:2015-10-15 20:36:02

标签: python heatmap seaborn

我在Python中使用Seaborn来创建Heatmap。我能够使用传入的值来注释单元格,但是我想添加表示单元格意味着什么的注释。例如,我不想仅仅看到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参数时,这是(工作)输出:

Working 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}

希望一切都有意义,我很感激任何人都能给予的帮助。

3 个答案:

答案 0 :(得分:27)

此功能刚刚在最新版本的Seaborn 0.7.1中添加。

  

来自Seaborn update history

     
    

除了布尔值之外,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 =&#39;&#39;如果您使用非数字标签,则必须使用,因为默认值为fmt =&#39; .2g&#39;这仅对数值有意义,并会导致文本标签出错。 enter image description here

答案 1 :(得分:4)

我不相信这在当前版本中是可行的。如果您正在进行黑客攻击,那么您可以执行以下操作......

# 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,以使所有标签均匀为黑色。

答案 2 :(得分:3)

Seaborn中的

aanot_kws有不同的用途,即提供对 注释的显示方式的访问权限,而不是 显示的内容

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

enter image description here