Integrate histogram in python?

jam picture jam · Apr 30, 2015 · Viewed 7.2k times · Source

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?

Answer

cphlewis picture cphlewis · Apr 30, 2015

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.