2016-07-07 447 views
4

我試圖繪製從-3到3的範圍內的對數比,並希望負比率爲綠色,正值爲紅色,對數比例爲0(中心)爲白色。 matplotlib中沒有預先存在的顏色方案提供此選項,我還無法弄清楚如何手動輸出一個不錯的漸變。如何在python中創建一個從綠色到紅色的熱圖?

+0

你可以勉強接受倒PiYG顏色表(綠色,中間的白色到粉紅色)。 – evtoh

+0

http://matplotlib.org/examples/pylab_examples/custom_cmap.html – user20160

回答

2

您可以使用LinearSegmentedColormap創建自己的。我喜歡將紅色和綠色通道的上限和下限設置爲小於1.0,所以顏色不太亮(這裏我使用了0.8)。調整以適應你的口味。

查看matplotlib網站上的custom_cmap example瞭解更多詳情。

下面是一個工作示例:

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

# This dictionary defines the colormap 
cdict = {'red': ((0.0, 0.0, 0.0), # no red at 0 
        (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white 
        (1.0, 0.8, 0.8)), # set to 0.8 so its not too bright at 1 

     'green': ((0.0, 0.8, 0.8), # set to 0.8 so its not too bright at 0 
        (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white 
        (1.0, 0.0, 0.0)), # no green at 1 

     'blue': ((0.0, 0.0, 0.0), # no blue at 0 
        (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white 
        (1.0, 0.0, 0.0)) # no blue at 1 
     } 

# Create the colormap using the dictionary 
GnRd = colors.LinearSegmentedColormap('GnRd', cdict) 

# Make a figure and axes 
fig,ax = plt.subplots(1) 

# Some fake data in the range -3 to 3 
dummydata = np.random.rand(5,5)*6.-3. 

# Plot the fake data 
p=ax.pcolormesh(dummydata,cmap=GnRd,vmin=-3,vmax=3) 

# Make a colorbar 
fig.colorbar(p,ax=ax) 

plt.show() 

enter image description here

+0

我會補充一點,使用綠紅色的地圖並不是一個好主意,因爲色彩鮮豔的人們無法解釋你的情節! – tom

2

如何使用以下LinearSegmentedColormap

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


cmapGR = LinearSegmentedColormap(
    'GreenRed', 
    { 
     'red': ((0.0, 0.0, 0.0), 
       (0.5, 1.0, 1.0), 
       (1.0, 1.0, 1.0)), 
     'green':((0.0, 1.0, 1.0), 
       (0.5, 1.0, 1.0), 
       (1.0, 0.0, 0.0)), 
     'blue': ((0.0, 0.0, 0.0), 
       (0.5, 1.0, 1.0), 
       (1.0, 0.0, 0.0)) 
    },) 

plt.imshow(np.array([np.arange(200) for i in range(200)]), cmap=cmapGR) 
plt.show() 

它產生以下enter image description here

見例如http://matplotlib.org/examples/pylab_examples/custom_cmap.html更多用途和其他例子。

-1

使用matplotlib.colors.LinearSegmentedColormapfrom_list方法似乎比這裏的一些其他的答案更直觀。

from matplotlib.colors import LinearSegmentedColormap 
cmap=LinearSegmentedColormap.from_list('rg',["r", "w", "g"], N=256) 

enter image description here

或爲更復雜的調整:

from matplotlib.colors import LinearSegmentedColormap 
c = ["darkred","red","lightcoral","white", "palegreen","green","darkgreen"] 
v = [0,.15,.4,.5,0.6,.9,1.] 
l = list(zip(v,c)) 
cmap=LinearSegmentedColormap.from_list('rg',l, N=256) 

enter image description here

相關問題