Plot a histogram such that bar heights sum to 1 (probability)

Viewed 172268

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.

6 Answers
  • The easiest solution is to use seaborn.histplot, or seaborn.displot with kind='hist', and specify stat='probability'
    • probability: or proportion: normalize such that bar heights sum to 1
    • density: normalize such that the total area of the histogram equals 1
    • data: pandas.DataFrame, numpy.ndarray, mapping, or sequence
  • seaborn is a high-level API for matplotlib
  • Tested in python 3.8.12, matplotlib 3.4.3, seaborn 0.11.2

Imports and Data

import seaborn as sns
import matplotlib.pyplot as plt

# load data
df = sns.load_dataset('penguins')

sns.histplot

  • axes-level plot
# create figure and axes
fig, ax = plt.subplots(figsize=(6, 5))

p = sns.histplot(data=df, x='flipper_length_mm', stat='probability', ax=ax)

enter image description here

sns.displot

  • figure-level plot
p = sns.displot(data=df, x='flipper_length_mm', stat='probability', height=4, aspect=1.5)

enter image description here

Since matplotlib 3.0.2, normed=True is deprecated. To get the desired output I had to do:

import numpy as np
data=np.random.randn(1000)
bins=np.arange(-3.0,3.0,51)
counts, _ = np.histogram(data,bins=bins)
if density: # equivalent of normed=True
    counts_weighter=counts.sum()
else: # equivalent of normed=False
    counts_weighter=1.0
plt.hist(bins[:-1],bins=bins,weights=counts/counts_weighter)

Trying to specify weights and density simultaneously as arguments to plt.hist() did not work for me. If anyone know of a way to get that working without having access to the normed keyword argument then please let me know in the comments and I will delete/modify this answer.

If you want bin centres then don't use bins[:-1] which are the bin edges - you need to choose a suitable scheme for how to calculate the centres (which may or may not be trivially derived).

Related