自定义注释Seaborn热图 [英] Custom Annotation Seaborn Heatmap

查看:104
本文介绍了自定义注释Seaborn热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 means. For example, instead of merely seeing 0.000000, I'd like to see the corresponding label, for instance "Foo," or 0.000000 (Foo).

用于热图功能的 Seaborn文档有点我认为这是关键的参数,很神秘:

The Seaborn documentation for the heatmap function is a bit cryptic with the parameter that I believe is the key here:

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.

I tried setting annot_kws to a dictionary of the aliases to the values, i.e., {'Foo' : -0.231049060187, 'Bar' : 0.000000}, etc., but I'm getting an AttributeError.

这是我的代码(为重现性,我在此处手动创建了数据数组):

Here is my code (I've manually created the data array here for reproducability):

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

Here is the (working) output when I don't use the annot_kws parameter:

这里,我时的堆栈跟踪包括annot_kws参数:

And here the stack trace for when I do include the annot_kws param:

---------------------------------------------------------------------------
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是我在堆栈跟踪中的该行中传递的属性,它是字典,基本上看起来像这样:

Finally, kws, the attribute I'm passing in the line in the stack trace, is the dictionary and it would look basically like this:

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

希望一切都有道理,任何人都能提供的帮助,我将不胜感激.

Hope everything makes sense, and I'd appreciate any help anyone can give.

推荐答案

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

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

来自季节性更新历史记录:

heatmap()的annot参数现在除了布尔值之外,还接受矩形数据集.如果传递了数据集,则其值将用于批注,而主数据集将用于热图单元格颜色

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

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.

这篇关于自定义注释Seaborn热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆