2012-03-14 238 views
35

我有一個簡單的圖像,我在matplotlib中用imshow顯示。我想應用自定義顏色映射,以便0-5之間的值爲白色,5-10爲紅色(非常簡單的顏色)等。我試過按照以下教程:在matplotlib中爲imshow定義離散色彩圖

http://assorted-experience.blogspot.com/2007/07/custom-colormaps.html使用以下代碼:

cdict = { 
'red' : ((0., 0., 0.), (0.5, 0.25, 0.25), (1., 1., 1.)), 
'green': ((0., 1., 1.), (0.7, 0.0, 0.5), (1., 1., 1.)), 
'blue' : ((0., 1., 1.), (0.5, 0.0, 0.0), (1., 1., 1.)) 
} 

my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 3) 

plt.imshow(num_stars, extent=(min(x), max(x), min(y), max(y)), cmap=my_cmap) 
plt.show() 

但是這最終顯示出奇怪的顏色,我只需要3-4種顏色,我想定義。我該怎麼做呢?

+0

類似的問題:http://stackoverflow.com/questions/9451545/using-matplotlib-to-draw-color-bar-with-distinguishable-and-uncontinues-colors/9451776#9451776 – 2012-03-15 17:35:41

回答

64

可以使用ListedColormap指定白色和紅色的色彩映射唯一的顏色和範圍確定,其中轉變是從一種顏色到下一個:

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

np.random.seed(101) 
zvals = np.random.rand(100, 100) * 10 

# make a color map of fixed colors 
cmap = colors.ListedColormap(['white', 'red']) 
bounds=[0,5,10] 
norm = colors.BoundaryNorm(bounds, cmap.N) 

# tell imshow about color map so that only set colors are used 
img = plt.imshow(zvals, interpolation='nearest', origin='lower', 
        cmap=cmap, norm=norm) 

# make a color bar 
plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0, 5, 10]) 

plt.savefig('redwhite.png') 
plt.show() 

由此得出的數字有隻有兩種顏色:

enter image description here

我基本上提出了同樣的事情有點不同的問題:2D grid data visualization in Python

該解決方案受matplotlib example的啓發。該示例解釋了bounds必須比使用的顏色數量多一個。

BoundaryNorm是將一系列值映射到整數,然後用於分配相應顏色的規範化。在上面的例子中,cmap.N只是定義了顏色的數量。