2013-10-02 24 views
4

我有一個Python直方圖。更改Python直方圖bin中的計數

我想將直方圖的峯值標準化爲1,這樣只有條的相對高度很重要。

我看到一些這樣做的方法,涉及更改箱寬度,但我不想這樣做。

我也意識到我可以改變y軸的標籤,但我也有另一個覆蓋的情節,所以yticks必須是實際值。

有沒有辦法訪問和更改每個bin中的「計數」直方圖?

謝謝。

回答

3

我認爲你所追求的是你的直方圖的歸一化形式,其中y軸是密度而不是計數。如果您使用的是Numpy,請使用histogram function中的normed標誌。

如果你希望你的直方圖的峯值爲1,那麼你可以通過最大窗口值除以每個倉計數,即(建設關SO MatPlotLib例子here):

#!/usr/bin/env python 
import matplotlib.pyplot as plt 
import numpy as np 

# Generate random data 
mu, sigma = 200, 25 
x = mu + sigma*np.random.randn(10000) 

# Create the histogram and normalize the counts to 1 
hist, bins = np.histogram(x, bins = 50) 
max_val = max(hist) 
hist = [ float(n)/max_val for n in hist] 

# Plot the resulting histogram 
center = (bins[:-1]+bins[1:])/2 
width = 0.7*(bins[1]-bins[0]) 
plt.bar(center, hist, align = 'center', width = width) 
plt.show() 

enter image description here

+0

但是,這不是將該區域歸一化爲1而不是峯值? – user1551817

+1

是的,非常正確。但它應該讓你輕鬆地比較酒吧的相對高度。如果您確實希望峯值爲1,那麼只需將每個箱體除以最大箱體的值即可。 – mdml

+0

對不起,如果我愚蠢的,但這是我的問題..我不知道如何分箱的特定值。 – user1551817