2013-12-12 117 views
0

我已經繪製Python中的直方圖,使用matplotlib,我需要y軸是概率,我無法找到如何做到這一點。例如,我希望它看起來類似於這樣http://www.mathamazement.com/images/Pre-Calculus/10_Sequences-Series-and-Summation-Notation/10_07_Probability/10-coin-toss-histogram.JPG製作柱狀圖概率的y軸,蟒蛇

這裏是我的代碼,我會在需要時

plt.figure(figsize=(10,10)) 
    mu = np.mean(a) #mean of distribution 
    sigma = np.std(a) # standard deviation of distribution 
    n, bins,patches=plt.hist(a,bin, normed=True, facecolor='white') 
    y = mlab.normpdf(bins, mu, sigma) 
    plt.plot(bins,y,'r--') 

    print np.sum(n*np.diff(bins))# proved the intergal over bars is unity 

    plt.show() 
+0

請添加您的數據(或代碼來生成它),並添加您的情節。 –

回答

2

只是除以樣本總數所有的樣本數藏漢附上了我的陰謀。這給出了概率而不是數量。

0

由於@SteveBarnes指出,通過樣本總數除以樣本數以獲得每個倉的概率。爲了得到一個與你鏈接的圖,你的「箱」應該是從0到10的整數。一個簡單的方法來計算離散分佈樣本的直方圖是np.bincount

下面是一個創建像你鏈接到一個情節片段:

import numpy as np 
import matplotlib.pyplot as plt 


n = 10 
num_samples = 10000 

# Generate a random sample. 
a = np.random.binomial(n, 0.5, size=num_samples) 

# Count the occurrences in the sample. 
b = np.bincount(a, minlength=n+1) 

# p is the array of probabilities. 
p = b/float(b.sum()) 

plt.bar(np.arange(len(b)) - 0.5, p, width=1, facecolor='white') 
plt.xlim(-0.5, n + 0.5) 
plt.xlabel("Number of heads (k)") 
plt.ylabel("P(k)") 

plt.show() 

plot