Search code examples
pythonmatplotlibplotintegral

Integrate histogram in python?


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 there a command like fig.integral(bin1, bin2)? That will return the integral of the histogram from bin1 to bin2?


Solution

  • 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.