Integrate histogram in python?

前端 未结 2 1340
自闭症患者
自闭症患者 2021-01-13 17:48

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 18:01

    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.

提交回复
热议问题