How to Plot Histogram from List of Data in Python?

In Python, the matplotlib library can be used to plot a histogram from a list of data. The list of data is first converted to a numpy array and then passed as an argument to the hist() function of matplotlib. This function creates a histogram which can be customized with labels, colors, and other parameters. After the histogram is created, it can be displayed, saved, or further analyzed.


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 .

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

x