【问题标题】:Python: matplotlib - probability mass function as histogramPython:matplotlib - 概率质量函数作为直方图
【发布时间】:2015-09-02 13:29:32
【问题描述】:

我想在同一张图上绘制直方图和折线图。但是,要做到这一点,我需要将直方图作为概率质量函数,所以我想在 y 轴上有一个概率值。但是,我不知道该怎么做,因为使用 normed 选项没有帮助。下面是我的源代码和使用过的数据的先睹为快。我将非常感谢所有建议。

data = [12565, 1342, 5913, 303, 3464, 4504, 5000, 840, 1247, 831, 2771, 4005, 1000, 1580, 7163, 866, 1732, 3361, 2599, 4006, 3583, 1222, 2676, 1401, 2598, 697, 4078, 5016, 1250, 7083, 3378, 600, 1221, 2511, 9244, 1732, 2295, 469, 4583, 1733, 1364, 2430, 540, 2599, 12254, 2500, 6056, 833, 1600, 5317, 8333, 2598, 950, 6086, 4000, 2840, 4851, 6150, 8917, 1108, 2234, 1383, 2174, 2376, 1729, 714, 3800, 1020, 3457, 1246, 7200, 4001, 1211, 1076, 1320, 2078, 4504, 600, 1905, 2765, 2635, 1426, 1430, 1387, 540, 800, 6500, 931, 3792, 2598, 5033, 1040, 1300, 1648, 2200, 2025, 2201, 2074, 8737, 324]
plt.style.use('ggplot')
plt.rc('xtick',labelsize=12)
plt.rc('ytick',labelsize=12)
plt.xlabel("Incomes")
plt.hist(data, bins=50, color="blue", alpha=0.5, normed=True)
plt.show() 

【问题讨论】:

  • normed 选项没有帮助是什么意思?你的问题到底是什么?如何规范分布?或者如何在直方图上画一条线?
  • @hitzig。我的问题正是我写的:“我想在 y 轴上有一个概率值。”文档后面的 normed 选项并不能保证 y 轴上的值描述概率(不要加起来到 1)。
  • normed 已弃用 hist()。请改用 density 关键字参数。

标签: python python-2.7 matplotlib plot histogram


【解决方案1】:

据我所知,matplotlib 没有内置此功能。但是,它很容易复制

    import numpy as np
    heights,bins = np.histogram(data,bins=50)
    heights = heights/sum(heights)
    plt.bar(bins[:-1],heights,width=(max(bins) - min(bins))/len(bins), color="blue", alpha=0.5)

编辑:这是a similar question 的另一种方法:

     weights = np.ones_like(data)/len(data)
     plt.hist(data, bins=50, weights=weights, color="blue", alpha=0.5, normed=False) 

【讨论】:

  • 当你通过 normed=True 时,它确实是这样的:values = values / sum(values)
  • 不,它没有,它产生一个概率密度函数,因此 bin 大小乘以高度总和为 1。见,例如stackoverflow.com/questions/3866520/…
  • 看看source,它确实看起来像每个 bin 取值并将其除以所有值的总和,不是吗?
  • m = (m.astype(float) / db) / m.sum() 是相关行。该 db 使一切变得不同,它使积分 f(x)dx 总和为 1,近似连续分布。 Op 希望 f(x) 总和为 1,近似离散分布。如果 bin 大小等于 1,则定义一致。否则,您需要执行类似我的回答的操作。查看概率质量函数与密度函数了解更多详情。
  • @mmdanziger 谢谢你的回答!第一个解决方案效果很好,非常有帮助。但当然,我也会检查第二个建议。我只是在除法期间添加了额外的“浮点”,因为我得到的是零而不是浮点值。
【解决方案2】:

这是旧的,但由于我发现它并在发现一些错误之前准备使用它,我想我会为我注意到的几个修复添加评论。在示例中@mmdanziger 使用plt.bar 中的bin 边缘,但是,您需要实际使用bin 的中心。他们还假设垃圾箱的宽度相等,这在“大多数”时间里都很好。但是你也可以给它传递一个宽度数组,这样你就不会不经意地忘记和犯错。所以这里有一个更完整的例子:

import numpy as np
heights, bins = np.histogram(data, bins=50)
heights = heights/sum(heights)
bin_centers = 0.5*(bins[1:] + bins[:-1])
bin_widths = np.diff(bins)
plt.bar(bin_centers, heights, width=bin_widths, color="blue", alpha=0.5)

@mmdanziger 将weights = np.ones_like(data)/len(data) 传递给 plt.hist() 的其他选项也可以做同样的事情,并且对于许多人来说是一种更简单的方法。

【讨论】:

  • 您能告诉我使用垃圾箱中心的目的是什么吗?
猜你喜欢
  • 2012-07-29
  • 2011-09-13
  • 2014-04-24
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 2020-03-09
  • 2017-10-17
  • 1970-01-01
相关资源
最近更新 更多