【问题标题】:How to get the area under a histogram in python如何在python中获取直方图下的区域
【发布时间】:2014-10-16 08:09:08
【问题描述】:

我一直在绘制直方图。我的代码如下所示:

x0=-15000
x1=15000
b=np.arange(x0,x1,(x1-x0)/250.)

plt.plot(b[0:-1], plt.hist(non_zeros(-e[0]), bins=b, normed=1, visible=0)[0], color = "k", label=r'$\gamma$ = 1.0')

我对直方图进行了归一化,因此曲线下的面积等于 1。e[0] 只是我从文档中获取的一些数据。

我现在想要的是仔细检查直方图下的 是否等于 1。如何做到这一点?

【问题讨论】:

  • 您能否添加一些代码,以便帮助您的人实际运行代码?包括你的导入,定义non_zeros,给e[0]一个示例值。
  • 只是对您的代码的评论,Python 具有正确的 True 和 False 布尔常量,它们在 1 和 0 以上是首选(因此您将拥有 normed=True, visible=False 而不是您拥有的)。
  • 这能回答你的问题吗? Integrate histogram in python?

标签: python matplotlib histogram area


【解决方案1】:

你可以这样计算面积:

import numpy
import matplotlib.pyplot as plt

x = numpy.random.randn(1000)

values, bins, _ = plt.hist(x, normed=True)
area = sum(numpy.diff(bins)*values)

【讨论】:

  • 非常感谢 chthonicdaemon,是否也可以找到 0.5% 和 99.5% 的分位数?
  • 您可以使用numpy.percentile 计算百分位数。
【解决方案2】:
import numpy as np
import matplotlib.pyplot as plt

x0=-15000
x1=15000
b=np.arange(x0,x1,(x1-x0)/250.)
values, bins, patches = plt.hist(b, 20 ,range=[-15000,15000], facecolor='green',normed=0, alpha=0.5)

#simply here you need to have the lenght of your bins to have a probability for under the graph

len_bins= len(bins)-1
#here is the totaly area under your histogram, which is supposed to be 1 as you want = suming up all the values for of all bins
Total_Area= sum(values[0:len_bins])/sum(values)
#so now lets say you want to have half of the area
Half_Area= sum(values[0:len_bins/2])/sum(values)

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 2012-07-08
    • 2013-05-16
    • 2020-10-02
    • 1970-01-01
    • 2011-05-17
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多