2014-12-05 75 views
2

我想繪製包含正數和負數的二維直方圖。我有下面的代碼使用pcolormesh,但我無法指定顏色級別強制白色對應於零(即,我希望我的顏色條在零周圍對稱)。我也試過imshow。matplotlib:如何指定二維歷史圖中的顏色水平

我知道你可以在plt.contour和plt.contourf中指定顏色級別,但是我找不到用塊繪製二維直方圖的方法。

任何意見將不勝感激。

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import cm as CM 

fig = plt.figure() 

# create an example histogram which is asymmetrical around zero 
x = np.random.rand(400) 
y = np.random.rand(400)  
Z, xedges, yedges = np.histogram2d(x, y, bins=10) 
Z = Z - 2. 

plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r) 

plt.colorbar() 
plt.savefig('test.png') 

enter image description here

回答

0

添加vminvmax參數與絕對值相等的

plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7) 

,看看你喜歡的結果

enter image description here

3

由於http://nbviewer.ipython.org/gist/pelson/5628989

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

x = np.random.rand(400) 
y = np.random.rand(400) 
Z, xedges, yedges = np.histogram2d(x, y, bins=10) 
Z = Z - 2. 
# -1 0 3 6 9 
cmap, norm = from_levels_and_colors([-1, 0, 3, 6, 9, 12], ['r', 'b', 'g', 'y', 'm']) # mention levels and colors here 
plt.pcolormesh(xedges, yedges, Z, cmap=cmap, norm=norm) 
plt.colorbar() 
plt.show() 

enter image description here

相關問題