Create a cumulative histogram in Matplotlib

Python

Matplotlib

Histogram

Create cumulative

Luc B.

Python

Matplotlib

Histogram

Cumulative histograms are much like normal histograms with one key difference: instead of each bar showing the bin quantity, each bar shows the bin quantity plus the quantity in all preceding bins. This means that the last bar of a cumulative histogram will have a value equal to the total number of samples.

Code Example

To create a cumulative histogram, use the cumulative argument to the plt.hist() function.

import matplotlib.pyplot as plt

values = [1, 1, 2, 3, 8, 7, 5, 4, 1, 3, 2, 4, 5, 8, 9]

# Create a cumulative histogram here
plt.hist(values, cumulative=True)

plt.ylabel("Quantity")
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 cumulative histogram here
ax.hist(values, cumulative=True)

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

png