我有一些形状为 (12,1) 的归一化直方图数据:
>>> hnorm
array([[ 0. ],
[ 0. ],
[ 0.01183432],
[ 0.0295858 ],
[ 0.04142012],
[ 0.04142012],
[ 0.03550296],
[ 0.01775148],
[ 1. ],
[ 0.98816568],
[ 0.56213018],
[ 0. ]])
我想以“热图”样式绘制它。我这样做是这样的:
import matplotlib.pyplot as plt
plt.imshow(hnorm, cmap='RdBu',origin='lower')
这有效(除了轴格式)。
但是,我想自定义颜色图以从白色渐变为红色。我尝试过:
import matplotlib.colors as col
cdict = {'red': ((0.00, 0.07, 0.14),
(0.21, 0.28, 0.35),
(0.42, 0.49, 0.56),
(0.63, 0.70, 0.77),
(0.84, 0.91, 0.99)),
'green': ((0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0),
(0.0, 0.0, 0.0))}
cmap1 = col.LinearSegmentedColormap('my_colormap',cdict,N=256,gamma=0.75)
plt.imshow(hnorm, cmap=cmap1,origin='lower')
这失败了。知道我做错了什么吗?
最佳答案
askewchan 建议的 cmap 'Reds' 更简单而且 (imo) 也更好看。但我的回答只是为了展示您构建自定义 cmap 的方法如何工作。
在您的颜色字典中,您有 5 个条目可以指定颜色。由于您只想使用红色和白色,因此您只需要两个实体。对于白色,必须使用由位置 0.0 处的颜色值 1.0 指定的所有颜色。对于红色,只应在位置 1.0 处使用红色。
您还只为红色元组提供值(0 除外)。这只会为您提供“全”红色和黑色之间的不同深浅的红色(因为您总是将绿色和蓝色设为 0)。
cdict = {'red': ((0.0, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0))}
my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict)
plt.imshow(np.random.rand(20,20), cmap=my_cmap, origin='lower', interpolation='none')
plt.colorbar(shrink=.75)
显示两个颜色项如何在 cmap 中“跳跃”的另一个示例:
cdict = {'red': ((0.0, 1.0, 1.0), # full red
(0.5, 1.0, 0.0), # full red till, no red after
(1.0, 1.0, 1.0)), # full red
'green': ((0.0, 1.0, 1.0), # full green
(0.5, 0.0, 0.0), # no green
(1.0, 1.0, 1.0)), # full green
'blue': ((0.0, 1.0, 1.0), # full blue
(0.5, 0.0, 1.0), # no blue till, full blue after
(1.0, 1.0, 1.0))} # full blue
my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict)
plt.imshow(np.random.rand(20,20), cmap=my_cmap, origin='lower', interpolation='none')
plt.colorbar(shrink=.75)
关于python - 自定义 matplotlib cmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18660758/