David Halley
David Halley

Reputation: 457

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?

Upvotes: 0

Views: 15095

Answers (2)

Hany Zekry
Hany Zekry

Reputation: 41

import numpy as np
import matplotlib.pyplot as plt

x0=-15000
x1=15000
b=np.arange(x0,x1,(x1-x0)/250.)
values, bins, patches = plt.hist(b, 20 ,range=[-15000,15000], facecolor='green',normed=0, alpha=0.5)

#simply here you need to have the lenght of your bins to have a probability for under the graph

len_bins= len(bins)-1
#here is the totaly area under your histogram, which is supposed to be 1 as you want = suming up all the values for of all bins
Total_Area= sum(values[0:len_bins])/sum(values)
#so now lets say you want to have half of the area
Half_Area= sum(values[0:len_bins/2])/sum(values)

Upvotes: 0

chthonicdaemon
chthonicdaemon

Reputation: 19760

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)

Upvotes: 7

Related Questions