2016-05-13 96 views
1

我遵循documentation來創建自定義顏色映射。地圖我想是這樣的:pcolor的自定義顏色映射

enter image description here

這是我想出了字典:

cdict = {'red': ((0.00, 0.0, 0.0), 
       (0.25, 1.0, 0.0), 
       (0.50, 0.0, 0.0), 
       (0.75, 1.0, 0.0), 
       (1.00, 1.0, 0.0)), 

    'green': ((0.00, 0.0, 0.0), 
       (0.25, 1.0, 1.0), 
       (0.50, 1.0, 1.0), 
       (0.75, 1.0, 1.0), 
       (1.00, 0.0, 0.0)), 

    'blue': ((0.00, 1.0, 1.0), 
       (0.25, 0.0, 0.0), 
       (1.00, 0.0, 0.0)) 
    } 

但它不給我我想要的結果。例如,值0.5使用紅色渲染。

這裏是代碼的其餘部分看起來像:

cmap = LinearSegmentedColormap('bgr', cdict) 
plt.register_cmap(cmap=cmap) 

plt.pcolor(dist, cmap='bgr') 
plt.yticks(np.arange(0.5, len(dist.index), 1), dist.index) 
plt.xticks(np.arange(0.1, len(dist.columns), 1), dist.columns, rotation=40) 

for y in range(dist.shape[0]): 
    for x in range(dist.shape[1]): 
     plt.text(x + 0.5, y + 0.5, dist.iloc[y,x], 
       horizontalalignment='center', 
       verticalalignment='center', rotate=90 
       ) 
plt.show() 

這裏所呈現的熱圖的示例:

enter image description here

我缺少什麼?

回答

1

之所以說0.5的顯示爲紅色在你的情節很可能只是因爲你的vminvmax不是0.0和1.0。大多數matplotlib 2D繪圖程序默認情況下將vmax設置爲數組中的最大值,在您的情況下它看起來像是0.53。如果您希望0.5爲綠色,請在致電pcolor時設置vmin=0.0, vmax=1.0

你的顏色表字典幾乎是正確的,但你擁有它現在有難以過渡到黃色/綠色在0.25和0.75點,你應該改變在「紅色」這些線路從

  (0.25, 1.0, 0.0), 
      (0.50, 0.0, 0.0), 
      (0.75, 1.0, 0.0), 

  (0.25, 1.0, 1.0), 
      (0.50, 0.0, 0.0), 
      (0.75, 1.0, 1.0), 

得到你想要的colorscale。這是結果:

corrected colorscale

0

看來你的彩色字典是錯誤的。例如,用於開始色彩映射的第一個條目是:

'red': (0.00, 0.0, 0.0) 
'green': (0.00, 0.0, 0.0) 
'blue': (0.00, 1.0, 1.0) 

它給出RGB = 001 =藍色。另外,我不確定LinearSegmentedColormap在某些時間間隔(如blue中的索引0.5)未定義時會如何運作。

這似乎給正確的結果:

import numpy as np 
import matplotlib.pyplot as pl 
from matplotlib.colors import LinearSegmentedColormap 

pl.close('all') 

cdict = { 
    'red': ((0.00, 1.0, 1.0), 
      (0.25, 1.0, 1.0), 
      (0.50, 0.0, 0.0), 
      (0.75, 1.0, 1.0), 
      (1.00, 0.0, 0.0)), 

    'green': ((0.00, 0.0, 0.0), 
      (0.25, 1.0, 1.0), 
      (0.50, 1.0, 1.0), 
      (0.75, 1.0, 1.0), 
      (1.00, 0.0, 0.0)), 

    'blue': ((0.00, 0.0, 0.0), 
      (0.25, 0.0, 0.0), 
      (0.50, 0.0, 0.0), 
      (0.75, 0.0, 0.0), 
      (1.00, 1.0, 1.0)) 
} 

cm_rgb = LinearSegmentedColormap('bgr', cdict) 

pl.figure() 
pl.imshow(np.random.random((20,20)), interpolation='nearest', cmap=cm_rgb) 
pl.colorbar() 

LinearSegmentedColormap文檔見the matplotlib docs

enter image description here

+1

哦,我看到我得到了彩色地圖圖像錯誤。不,這個詞是對的,這只是圖像必須是反映ti的一面鏡子。我只是修正了這一點。問題是.5的值被映射爲紅色而不是綠色。你提供的文檔鏈接清楚地表明r,g,b條目不需要對齊。在這個例子中,其中一個顏色分量比其他顏色分量有更多的間隔。 –