绘制直方图,使总高度等于1 [英] Plot a histogram such that the total height equals 1

查看:36
本文介绍了绘制直方图,使总高度等于1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是answer的后续问题。我正在尝试绘制归一化直方图,但得到的不是y轴上的最大值1,而是不同的数字。

对于数组k=(1,4,3,1)

 import numpy as np

 def plotGraph():
   
    import matplotlib.pyplot as plt
    
    k=(1,4,3,1)

    plt.hist(k, normed=1)

    from numpy import *
    plt.xticks( arange(10) ) # 10 ticks on x axis

    plt.show()  
    
plotGraph()

我得到这个直方图,它看起来不像是规格化的。

对于不同的数组,k=(3,3,3,3)

 import numpy as np

 def plotGraph():
   
    import matplotlib.pyplot as plt
    
    k=(3,3,3,3)

    plt.hist(k, normed=1)

    from numpy import *
    plt.xticks( arange(10) ) # 10 ticks on x axis

    plt.show()  
    
plotGraph()

我得到的直方图的最大y值为10。

对于不同的k,即使Normded=1或Normed=True,我也会获得不同的y的最大值。

为什么规范化(如果有效)会根据数据进行更改,以及如何使y的最大值等于1?

更新:

我正在尝试实现来自plotting histograms whose bar heights sum to 1 in matplotlibCarsten König答案,但得到非常奇怪的结果:

import numpy as np

def plotGraph():

    import matplotlib.pyplot as plt

    k=(1,4,3,1)

    weights = np.ones_like(k)/len(k)
    plt.hist(k, weights=weights)

    from numpy import *
    plt.xticks( arange(10) ) # 10 ticks on x axis

    plt.show()  

plotGraph()

结果:

我做错了什么?

推荐答案

绘制归一化直方图时,曲线下的面积总和应为1,而不是高度。

In [44]:

import matplotlib.pyplot as plt
k=(3,3,3,3)
x, bins, p=plt.hist(k, density=True)  # used to be normed=True in older versions
from numpy import *
plt.xticks( arange(10) ) # 10 ticks on x axis
plt.show()  
In [45]:

print bins
[ 2.5  2.6  2.7  2.8  2.9  3.   3.1  3.2  3.3  3.4  3.5]

在此示例中,箱宽为0.1,曲线下面的面积总和为1(0.1*10)。

x存储每个垃圾箱的高度。p存储每个单独的存储箱对象(实际上,它们是patches。因此,我们只需汇总x并修改每个bin对象的高度。

若要使高度之和为1,请在plt.show()之前添加以下内容:

for item in p:
    item.set_height(item.get_height()/sum(x))

这篇关于绘制直方图,使总高度等于1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆