Home » How to Plot Histogram from List of Data in Python

How to Plot Histogram from List of Data in Python

by Tutor Aspire

You can use the following basic syntax to plot a histogram from a list of data in Python:

import matplotlib.pyplot as plt

#create list of data
x = [2, 4, 4, 5, 6, 6, 7, 8, 14]

#create histogram from list of data
plt.hist(x, bins=4)

The following examples show how to use this syntax in practice.

Example 1: Create Histogram with Fixed Number of Bins

The following code shows how to create a histogram from a list of data, using a fixed number of bins:

import matplotlib.pyplot as plt

#create list of data
x = [2, 4, 4, 5, 6, 6, 7, 7, 7, 8, 8, 8, 12, 13]

#create histogram with 4 bins
plt.hist(x, bins=4, edgecolor='black')

Example 2: Create Histogram with Specific Bin Ranges

The following code shows how to create a histogram from a list of data, using specified bin ranges:

import matplotlib.pyplot as plt

#create list of data
x = [2, 4, 4, 5, 6, 6, 7, 7, 7, 8, 8, 8, 12, 13]

#specify bin start and end points
bin_ranges = [0, 5, 10, 15]

#create histogram with 4 bins
plt.hist(x, bins=bin_ranges, edgecolor='black')

You can find the complete documentation for the Matplotlib histogram function here.

Additional Resources

The following tutorials explain how to create other commonly used charts in Matplotlib:

How to Plot a Time Series in Matplotlib
How to Create Boxplots by Group in Matplotlib
How to Increase Plot Size in Matplotlib

You may also like