简体   繁体   English

seaborn/matplotlib 自定义颜色图

[英]seaborn/matplotlib custom colormap

I've a 2d numpy array which I want to plot showing different colors to regions (blue for data < 0, green for 0 <= data < 5 and red for data > 5).我有一个二维 numpy 数组,我想要 plot 显示不同的 colors 到区域(蓝色表示数据 < 0,红色表示 0 <= 数据 >)

In essence, I'm trying to use categorical colors for continuous data based on data range.本质上,我正在尝试使用分类 colors 基于数据范围的连续数据。

Currently I'm using numexpr on data using expression (1 * (data < 0)) + (2 * (data >= 0) & (data < 5)) + (3 * (data >= 5)) .目前我正在使用表达式(1 * (data < 0)) + (2 * (data >= 0) & (data < 5)) + (3 * (data >= 5))对数据使用numexpr Then using indexed color array/dict ( {1: (0, 0, 255), 2: (0, 255, 0), 3: (255, 0, 0)} ) to compute color values for data.然后使用索引颜色数组/字典( {1: (0, 0, 255), 2: (0, 255, 0), 3: (255, 0, 0)} )计算数据的颜色值。 I think this is overkill.我认为这是矫枉过正。 There must be an easy way to do this using seaborn/matplot using custom colormaps, which I could not find.必须有一种简单的方法来使用 seaborn/matplot 使用自定义颜色图,但我找不到。 Any pointers/sample code would be greatly helpful.任何指针/示例代码都会非常有帮助。

You can create a custom color map and use sns.heatmap with vmin=-1, vmax=6 :您可以创建自定义颜色 map 并将sns.heatmapvmin=-1, vmax=6一起使用:

# random data
np.random.seed(1)
a = np.random.uniform(-2,10,(10,10))

from matplotlib import cm, colors as mcolors

# create a custome color map
cmap = mcolors.ListedColormap(['b']+['g']*5 + ['r'], name='abcd', N=7)

# plot heat map, annotation for reference
sns.heatmap(a, annot=True,xticklabels=False, yticklabels=False, cmap=cmap, vmin=-1,vmax=6)

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM