2013-12-12 118 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