seaborn heatmap获取颜色代码值数组 [英] seaborn heatmap get array of color codes values

查看:331
本文介绍了seaborn heatmap获取颜色代码值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取与热图的每个单元格关联的颜色代码:

I am trying to get the color codes associated with each cell of a heatmap:

import seaborn as sns
import numpy as np
import matplotlib.cm as cm

hm = sns.heatmap(
np.random.randn(10,10),
cmap = cm.coolwarm)

# hm.<some function>[0][0] would return the color code of the cell indexed (0,0)


推荐答案

因为 sns.heatmap 返回 matplotlib 轴对象,我们不能真正直接使用 hm 。但是我们可以使用 cmap 对象本身来返回数据的rgba值。 编辑代码已更新,包括数据标准化。

Because sns.heatmap returns a matplotlib axis object, we can't really use hm directly. But we can use the cmap object itself to return the rgba values of the data. Edit Code has been updated to include normalization of data.

from matplotlib.colors import Normalize

data = np.random.randn(10, 10)
cmap = cm.get_cmap('Greens')
hm = sns.heatmap(data, cmap=cmap)

# Normalize data
norm = Normalize(vmin=data.min(), vmax=data.max())
rgba_values = cmap(norm(data))

所有颜色现在都包含在 rgba_values 中。因此,要获得热图中左上角正方形的颜色,您可以简单地做

All of the colors are now contained in rgba_values. So to get the color of the upper left square in the heatmap you could simply do

In [13]: rgba_values[0,0]
Out[13]: array([ 0.        ,  0.26666668,  0.10588235,  1.        ])

有关更多信息,请查看从matplotlib中的彩色地图

For more, check out Getting individual colors from a color map in matplotlib

更新

要在调用<$时使用 center robust 关键字来重新调整颜色图c $ c> sns.heatmap ,您基本上只需重新定义 vmin vmax 。查看相关的seaborn源代码( http:// github。 com / mwaskom / seaborn / blob / master / seaborn / matrix.py#L202 ),以下更改为 vmin vmax 应该可以解决问题。

To readjust the colormap from using the center and robust keywords in the call to sns.heatmap, you basically just have to redefine vmin and vmax. Looking at the relevant seaborn source code (http://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py#L202), the below changes to vmin and vmax should do the trick.

data = np.random.randn(10, 10)
center = 2
robust = False
cmap = cm.coolwarm
hm = sns.heatmap(data, cmap=cmap, center=center, robust=robust)

vmin = np.percentile(data, 2) if robust else data.min()
vmax = np.percentile(data, 98) if robust else data.max()
vmin += center
vmax += center

norm = Normalize(vmin=vmin, vmax=vmax)
rgba_values = cmap(norm(data))

这篇关于seaborn heatmap获取颜色代码值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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