Is there a simple command in matplotlib that let\'s me take the integral of histogram over a certain range? If I plot a histogram with: fig = plt.hist(x, bins) Then, is
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.
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.