Integrate histogram in python?

喜欢而已 提交于 2019-12-05 16:59:38

First, remember that the integral is just the total area underneath the curve. In the case of a histogram, the integral (in pseudo-python) is sum([bin_width[i] * bin_height[i] for i in bin_indexes_to_integrate]).

As a reference, see this example of using a histogram in matplotlib: http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html.

Here they separate the output of the plt.histogram into three parts, n, bins, and patches. We can use this separation to implement the "integral" you request like so.

Assuming bin1 and bin2 are indexes of the bins you want to integrate, then calculate the integral like so:

# 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])

If you've defined bins to be a list with multiple widths, you have to do something like what @cphlewis said (this works w/ no off by one):

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

It's also worth taking a look at the API documentation for matplotlib.pyplot.hist.

The plt.hist command returns all the data you need to make one. If out = plt.hist(...), the bin heights are in out[0] and the bin widths are diff(out[1]). E.g.,

sum(out[0][4:7]*diff(out[1][4:8]))

for the integral over bins 4-6 inclusive. diff calculates each bin-width, so it handles bins of different widths, and the multiplication happens element-wise, so calculates the areas of each rectangle in the histogram.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!