2014-02-06 147 views
1

我有一組N個具有兩個屬性的對象:x和y。 我想使用hist()在MATPLOTLIB中描述x的分佈情況。很簡單。現在,我想用顏色代表直方圖中每個條的顏色代碼,該顏色表示該顏色映射中該集的y的平均值。是否有捷徑可尋?這裏,x和y都是N-D numpy數組。謝謝!對直方圖進行顏色編碼

fig = plt.figure() 
n, bins, patches = plt.hist(x, 100, normed=1, histtype='stepfilled') 
plt.setp(patches, 'facecolor', 'g', 'alpha', 0.1) 
plt.xlabel('x') 
plt.ylabel('Normalized frequency') 
plt.show() 
+1

你捕捉'patches'對象返回,你就不能通過迭代基於'bins'並設置顏色,你認爲合適? –

+0

因此,我將不得不手動檢查它們所在的N個對象中的每一個,在那裏記錄y,並最終取平均值y來確定顏色? – Cokes

+0

就是這樣的;首先,我可能將x和y組合成一個數組,然後按x排序。之後,迭代數據,然後求和,然後求平均值和着色,當你看到x跨過邊界。 –

回答

1
import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
# set up the bins 
Nbins = 10 
bins = np.linspace(0, 1, Nbins +1, endpoint=True) 
# get some fake data 
x = np.random.rand(300) 
y = np.arange(300) 
# figure out which bin each x goes into 
bin_num = np.digitize(x, bins, right=True) - 1 
# compute the counts per bin 
hist_vals = np.bincount(bin_num) 
# set up array for bins 
means = np.zeros(Nbins) 
# numpy slicing magic to sum the y values by bin 
means[bin_num] += y 
# take the average 
means /= hist_vals 

# make the figure/axes objects 
fig, ax = plt.subplots(1,1) 
# get a color map 
my_cmap = cm.get_cmap('jet') 
# get normalize function (takes data in range [vmin, vmax] -> [0, 1]) 
my_norm = Normalize() 
# use bar plot 
ax.bar(bins[:-1], hist_vals, color=my_cmap(my_norm(means)), width=np.diff(bins)) 

# make sure the figure updates 
plt.draw() 
plt.show() 

相關:vary the color of each bar in bargraph using particular value

+0

數字化的「right」選項可在我的Ubuntu機器上使用,但不能在我的Mac上使用......嗯。 與:http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html without:http://docs.scipy.org/doc/numpy-1.6.0/reference/generated /numpy.digitize.html – Cokes

+0

注意版本,1.8和1.6。更新你的mac;) – tacaswell

+0

請參閱http://stackoverflow.com/questions/21619347/creating-a-python-histogram-without-pylab/21632623#21632623你可以複製'數字化'的功能,一次通過'x' – tacaswell