Plot multiple histograms with adjacent bars in Matplotlib

Python

Matplotlib

Histogram

Create grouped

Luc B.

Python

Matplotlib

Histogram

Histograms are powerful visualizations that show the number of occurrences for each value of a variable, creating a distribution of results. Sometimes it's useful to plot multiple distributions in a single plot where bars from different distributions are adjacent to each other. This is often called a grouped histogram, and it's easily accomplished using Matplotlib.

A visualization with similar applications is the stacked histogram. Furthermore, it's sometimes clearer to overlay the histograms instead of placing multi-colored bars right next to each other.

Code Example

To create plot with multiple histograms for different groups, organize your data into separate arrays according to their group and pass them to plt.hist().

import matplotlib.pyplot as plt

group1 = [1, 1, 1, 2, 2, 3, 4]
group2 = [2, 2, 2, 1, 1, 3, 1, 4]

# Create a stacked histogram here
plt.hist([group1, group2],
         bins=[1, 2, 3, 4, 5], rwidth=0.9, align="left")

plt.legend(["Group 1", "Group 2"])
plt.xticks([1, 2, 3, 4])
plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()

png

To plot additional histograms, simply add more arrays to the list passed to plt.hist(). These arrays do not need to be the same length, as plt.hist() simply counts the occurrences different values in each array.