Python:matplotlib - 概率质量函数作为直方图

Ziv*_*iva 2 python plot matplotlib histogram python-2.7

我想在同一个图形上绘制直方图和线图.但是,要做到这一点,我需要将直方图作为概率质量函数,所以我希望在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() 
Run Code Online (Sandbox Code Playgroud)

mmd*_*ger 5

据我所知,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)
Run Code Online (Sandbox Code Playgroud)

编辑:以下是来自类似问题的另一种方法:

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

  • 不,它没有,它产生概率密度函数,使得箱子大小乘以高度总和为1.请参阅http://stackoverflow.com/questions/3866520/plotting-histograms-whose-bar-heights-sum-to-1-in-matplotlib (4认同)
  • `m =(m.astype(float)/ db)/ m.sum()`是相关的行.这个数据库完全不同,它使积分f(x)dx总和为1,接近连续分布.Op希望f(x)总和为1,近似于离散分布.如果bin大小等于1,则定义重合.否则,你需要做我的回答.查找概率质量函数与密度函数以获取更多详细信息. (2认同)