自定义颜色映射 Matplotlib,使一个值成为规定的颜色 [英] Custom colour maps Matplotlib, make one value a prescribed colour

查看:58
本文介绍了自定义颜色映射 Matplotlib,使一个值成为规定的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中有一个数组,使用 matplotlib,浮点数介于 0 和 1 之间.

I have an array in python, using matplotlib, with floats ranging between 0 and 1.

我正在使用 imshow 显示这个数组,我正在尝试创建一个与 Greens 相同的自定义 cmap,但是当一个单元格变为 0 时,我希望能够将该值映射到红色,并保留其余部分光谱不变.

I am displaying this array with imshow, I am trying to create a custom cmap, which is identical to Greens, however when a cell becomes 0 I would like to be able to map that value to red, and leave the rest of he spectrum unchanged.

如果有人更熟悉 matplotlib 能够帮助我,我将不胜感激!

If anyone more familiar with matplotlib would be able to help me I would greatly appreciate it!

例如,我将如何编辑此脚本以使矩阵中的零值显示为红色?

For instance how would I edit this script so that the zero value in the matrix showed as red?

import numpy as np

from matplotlib import pyplot as plt

import matplotlib

x = np.array([[0,1,2],[3,4,5],[6,7,8]])

fig = plt.figure()

cmap_custom = matplotlib.cm.Greens

plt.imshow( x, interpolation='nearest' ,cmap = cmap_custom)

plt.colorbar()

plt.show()

推荐答案

matplotlib中的色图允许您为超出定义范围的值设置特殊颜色.在您的情况下,请使用 cmap_custom.set_under('r')为低于定义范围的值指定颜色.然后您还需要指定范围的下限:vmin=0.01(只是某个值 > 0).最后使用 plt.colorbar(extend='min') 创建颜色条.

The colormaps in matplotlib allow you to set special colors for values that are outside of the defined range. In your case specify the color for values below the defined range with cmap_custom.set_under('r'). Then you also need to specify the lower end of the range: vmin=0.01 (just some value > 0). Finally create the colorbar with plt.colorbar(extend='min').

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

x = np.array([[0,1,2],[3,4,5],[6,7,8]])

fig = plt.figure()
cmap_custom = matplotlib.cm.Greens
cmap_custom.set_under('r')
plt.imshow( x, interpolation='nearest' ,cmap = cmap_custom, vmin=0.01)
plt.colorbar(extend='min')
plt.show()

这篇关于自定义颜色映射 Matplotlib,使一个值成为规定的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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