在python中集成直方图?

在matplotlib中是否有一个简单的命令让我在一定范围内获取直方图的积分?如果我绘制直方图:
     fig = plt.hist(x,bins)
那么,有没有像fig.integral(bin1,bin2)这样的命令?这将返回从bin1到bin2的直方图的积分?

解决方法:

首先,请记住积分只是曲线下面的总面积.在直方图的情况下,积分(在伪python中)是sum(bin_indexes_to_integrate中的i的[bin_width [i] * bin_height [i]]).

作为参考,请参阅matplotlib:http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html中使用直方图的示例.

在这里,他们将plt.histogram的输出分为三个部分,n,bins和patch.我们可以使用这种分离来实现您所要求的“整体”.

假设bin1和bin2是要集成的bin的索引,那么计算积分如下:

# create some dummy data to make a histogram of
import numpy as np
x = np.random.randn(1000)
nbins = 10
# use _ to assign the patches to a dummy variable since we don't need them
n, bins, _ = plt.hist(x, nbins)

# get the width of each bin
bin_width = bins[1] - bins[0]
# sum over number in each bin and mult by bin width, which can be factored out
integral = bin_width * sum(n[bin1:bin2])

如果您已经将bin定义为具有多个宽度的列表,则必须执行类似@cphlewis所说的内容(这样可以不用一个):

integral = sum(np.diff(bins[bin1:bin2])*n[bin1:bin2]) 

这也值得一看API documentation for matplotlib.pyplot.hist.

上一篇:一些对于错排问题的简单思考


下一篇:Solution -「ZJOI 2020」「洛谷 P6631」序列