How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

user248237 picture user248237 · Oct 5, 2010 · Viewed 145.8k times · Source

I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following:

plt.hist(myarray, normed=True)

as well as:

plt.hist(myarray, normed=1)

but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1. I'd like to produce such a histogram -- how can I do it?

Answer

Carsten König picture Carsten König · May 6, 2013

If you want the sum of all bars to be equal unity, weight each bin by the total number of values:

weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)

Hope that helps, although the thread is quite old...

Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division