为颜色图和颜色栏中的两个(或多个)特定值添加单独的颜色 [英] Add separate colors for two (or more) specific values in color plot and color bar

查看:95
本文介绍了为颜色图和颜色栏中的两个(或多个)特定值添加单独的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在颜色图中显示一个矩阵,并为两个或多个特殊值指定特定的颜色.

I want to show a matrix in color plot and give specific colors to two or more special values.

import numpy as np
from pylab import *

np.random.seed(10)    
a=np.random.randint(-1,10, size=(5, 5))
print a

fig, ax = plt.subplots()
mat=ax.matshow(a, cmap=cm.jet, vmin=1, vmax=10)
colorbar(mat)
show()

这是a矩阵的值:

[[ 8  3 -1  0  8]
 [-1  0  9  7  8]
 [-1  9  7  5  3]
 [ 2 -1  3  5  7]
 [ 9  0  7  3  0]]

这是情节:
我想将黑色分配给所有-1条目,将白色分配给所有0条目,并且我希望将其显示在数字栏下面的颜色栏上,作为两种不连续的颜色.这是一个示例,我的照片编辑能力很差,但是应该清楚我想要的内容(颜色条应按比例绘制):
对我来说,连续的jet色彩图并不重要,我对我的色条是离散的并且由例如10种颜色组成的解决方案感到满意,其中10种颜色包括黑白两种,其中8种来自jet色彩图颜色.但是,无论值的总范围是多少,重要的是-1和0具有不同的颜色.
例如,如果值范围是-1至1000:

Here is the plot:
I'd like to assign black color to all -1 entries and white to all 0 entries, and I'd like it to be shown on color bar below number one as two discrete colors. Here is an example, my photo editing skills are poor, but it should be clear what I want (color bar should be in scale):
It's not important to me to have a continuous jet color map, I'd be satisfied with a solution where my color bar would be discrete, and consisted of, for example 10 colors, of which two would be black and white, 8 from jet color map colors. However, it's important that -1 and 0 have distinct colors, no matter what the total range of values is.
For example if value range was from -1 to 1000:

推荐答案

您可以使用ListedColormap:

You can use ListedColormap:

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

N = 10

np.random.seed(10)    
a=np.random.randint(-1, N, size=(5, 5))
print a

fig, ax = plt.subplots()

colors = [(0.0,0.0,0.0),(1.0,1.0,1.0)]
colors.extend(mpl.cm.jet(np.linspace(0, 1, N-1)))
cmap = mpl.colors.ListedColormap(colors)
mat=ax.matshow(a, cmap=cmap, vmin=-1, vmax=N-1)
cax = plt.colorbar(mat, ticks=np.linspace(-0.5, N-1-0.5, N+1))
cax.set_ticklabels(range(-1, N))
plt.show()

对于值范围,您可以先将值转换为范围索引.

for value ranges, you can convert the values to range index first.

这篇关于为颜色图和颜色栏中的两个(或多个)特定值添加单独的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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