Search code examples
pythonmatplotlibhistogramarea

How to get the area under a histogram in python


I have been plotting a histogram. My code looks like this:

x0=-15000
x1=15000
b=np.arange(x0,x1,(x1-x0)/250.)

plt.plot(b[0:-1], plt.hist(non_zeros(-e[0]), bins=b, normed=1, visible=0)[0], color = "k", label=r'$\gamma$ = 1.0')

I normed the histogram so the area under the curve is equal to 1. e[0] is just some data i take in from a document.

What i want now is to double check that the are under the histogram is equal to one. How can this be done?


Solution

  • You can calculate the area in this way:

    import numpy
    import matplotlib.pyplot as plt
    
    x = numpy.random.randn(1000)
    
    values, bins, _ = plt.hist(x, normed=True)
    area = sum(numpy.diff(bins)*values)