无法在Matplotlib直方图上获得y轴以显示概率

乔尔

我有数据(PD系列),看起来像(每日股票回报,n = 555):

S = perf_manual.returns
S = S[~((S-S.mean()).abs()>3*S.std())]

2014-03-31 20:00:00    0.000000
2014-04-01 20:00:00    0.000000
2014-04-03 20:00:00   -0.001950
2014-04-04 20:00:00   -0.000538
2014-04-07 20:00:00    0.000764
2014-04-08 20:00:00    0.000803
2014-04-09 20:00:00    0.001961
2014-04-10 20:00:00    0.040530
2014-04-11 20:00:00   -0.032319
2014-04-14 20:00:00   -0.008512
2014-04-15 20:00:00   -0.034109
...

我想据此生成一个概率分布图。使用:

print stats.normaltest(S)

n, bins, patches = plt.hist(S, 100, normed=1, facecolor='blue', alpha=0.75)
print np.sum(n * np.diff(bins))

(mu, sigma) = stats.norm.fit(S)
print mu, sigma
y = mlab.normpdf(bins, mu, sigma)
plt.grid(True)
l = plt.plot(bins, y, 'r', linewidth=2)

plt.xlim(-0.05,0.05)
plt.show()

我得到以下内容:

NormaltestResult(statistic=66.587382579416982, pvalue=3.473230376732532e-15)
1.0
0.000495624926242 0.0118790391467

图形

我的印象是y轴是一个计数,但我想使用概率。我怎么做?我已经尝试了很多StackOverflow答案,但无法弄清楚。

某事

(据我所知)没有简单的方法可以使用进行操作plt.hist但是您可以简单地使用来对数据进行装箱np.histogram,然后以任何所需的方式对数据进行标准化。如果我对您的理解正确,则希望数据显示在给定仓中找到点的概率,而不是概率分布。这意味着您必须按比例缩放数据,以使所有bin的总和为1 bin_probability = n/float(n.sum())

然后,您将不再具有正确归一化的概率分布函数(pdf),这意味着区间上的积分将不再是概率!这就是为什么您必须重新调整比例mlab.normpdf以使其具有与直方图相同的范数的原因所需的因子只是容器宽度,因为当您从正确归一化的合并pdf开始时,所有容器上的总和乘以它们各自的宽度即为1。现在,您要使容器的总和等于1。因此缩放因子为垃圾箱宽度。

因此,您最终得到的代码类似于以下内容:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

# Produce test data
S = np.random.normal(0, 0.01, size=1000)

# Histogram:
# Bin it
n, bin_edges = np.histogram(S, 100)
# Normalize it, so that every bins value gives the probability of that bin
bin_probability = n/float(n.sum())
# Get the mid points of every bin
bin_middles = (bin_edges[1:]+bin_edges[:-1])/2.
# Compute the bin-width
bin_width = bin_edges[1]-bin_edges[0]
# Plot the histogram as a bar plot
plt.bar(bin_middles, bin_probability, width=bin_width)

# Fit to normal distribution
(mu, sigma) = stats.norm.fit(S)
# The pdf should not normed anymore but scaled the same way as the data
y = mlab.normpdf(bin_middles, mu, sigma)*bin_width
l = plt.plot(bin_middles, y, 'r', linewidth=2)

plt.grid(True)
plt.xlim(-0.05,0.05)
plt.show()

结果图片将是:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章