Convert a histogram to a probability density plot in Matplotlib

Python

Matplotlib

Histogram

Create probability density

Luc B.

Python

Matplotlib

Histogram

Histograms are key tools for understanding the distribution of measurements in a system. It is often necessary to convert histograms into probability density plots so analysts can compute the probability that a measurement falls in a certain window.

Code Example

To create a probability density plot from a histogram, use the density argument to the plt.hist() function.

import matplotlib.pyplot as plt

values = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5]

# Create a probability density histogram here
plt.hist(values, density=True, bins=5, rwidth=0.9)

plt.ylabel("Probability Density")
plt.xlabel("Value")
plt.show()

png

More Examples

Object Oriented Interface

The same functionality is easily accomplised using Matplotlib's object oriented interface.

ax = plt.axes()

# Create a probability density histogram here
ax.hist(values, density=True, bins=5, rwidth=0.9)

ax.set_ylabel("Quantity")
ax.set_xlabel("Value")
plt.show()

png