【问题标题】:How to plot normalized histogram with pdf properly using matplotlib?如何使用matplotlib正确绘制带有pdf的标准化直方图?
【发布时间】:2018-09-20 11:02:49
【问题描述】:

我尝试使用来自numpy.random.normal documentation 的示例绘制归一化直方图。为此,我生成了正态分布的随机样本。

mu_true = 0
sigma_true = 0.1 
s = np.random.normal(mu_true, sigma_true, 2000)

然后我将正态分布拟合到数据并计算 pdf。

mu, sigma = stats.norm.fit(s)
points = np.linspace(stats.norm.ppf(0.01,loc=mu,scale=sigma),
                 stats.norm.ppf(0.9999,loc=mu,scale=sigma),100)
pdf = stats.norm.pdf(points,loc=mu,scale=sigma)

显示拟合的 pdf 和数据直方图。

plt.hist(s, 30, density=True);
plt.plot(points, pdf, color='r')
plt.show() 

我使用density=True,但很明显,pdf 和直方图没有标准化。

对于绘制真正归一化的直方图和 pdf 有什么建议?

Seaborn distplot 也不能​​解决问题。

import seaborn as sns
ax = sns.distplot(s)

【问题讨论】:

  • 只是让您知道:Seaborn 的 distplot 完成了所有这些工作。
  • 谢谢。但这无济于事。我已经编辑了问题。
  • 你确定它没有标准化吗?直方图下方的区域是多少?
  • 总面积为 1。我被垃圾箱的高度弄糊涂了。但现在一切都清楚了

标签: python matplotlib histogram


【解决方案1】:

是什么让你认为它没有标准化?猜测一下,这可能是因为每列的高度扩展到大于 1 的值。但是,这种想法是有缺陷的,因为在归一化的直方图/pdf 中,它下面的总面积应该总和为 1(而不是高度)。当您处理 x 中小于一的小步骤时(就像您一样),那么列高大于一也就不足为奇了!

您可以在链接的 scipy 示例中清楚地看到这一点:x 值要大得多(一个数量级),因此它们的 y 值也更小。如果您更改分布以涵盖更广泛的值,您将看到相同的效果。试试 sigma 10 而不是 0.1,看看会发生什么!

【讨论】:

    【解决方案2】:
    import numpy as np
    from numpy.random import seed, randn
    from scipy.stats import norm
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_theme()
    
    "Try this, for ? = 0"
    seed(0)
    points = np.linspace(-5,5,100)
    pdf    = norm.pdf(points,0,1)
    plt.plot(points, pdf, color='r')
    plt.hist(randn(50), density=True);
    plt.show() 
    
    
    "or this, for ? = 10"
    seed(0)
    points = np.linspace(5,15,100)
    pdf    = norm.pdf(points,10,1)
    plt.plot(points, pdf, color='r')
    plt.hist(10+randn(50), density=True);
    plt.show() 
    

    【讨论】:

    • 我建议您包含您的代码的照片结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2016-06-09
    • 2015-10-25
    相关资源
    最近更新 更多