Create a histogram in Matplotlib

Python

Matplotlib

Histogram

Create

Luc B.

Python

Matplotlib

Histogram

Histograms are immensely powerful visualizations that show the number of occurrences for each value of a variable, creating a distribution of results. If a variable is a continuous value, occurrences are grouped into bins. For example, when analyzing a school's test results, we could count the number of students who scored in the range 100% to 95%, 95% to 90%, 90% to 85%, etc.

Since histograms are a special case of bar charts, the can be created with plt.bar(). However, this requires manually binning the values. With, Matplotlib's plt.hist(), users can pass in raw data and Matplotlib will automatically bin and count the values to produce a histogram.

Code Example

To create a histogram use 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 histogram here
plt.hist(values)

plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()

png

Matplotlib allows for many histogram customizations: