Plot Histogram in Python

Introduction

We can use hist() in Matplotlib, pandas, and seaborn to plot histograms in Python. The following is the basic syntax of plotting histogram using these 3 different modules.

Method 1: Using matplotlib

plt.hist(data,bins=’auto’)

Method 2: Using pandas

pd.hist()

Method 3: Using seaborn

sns.histplot(data=dataset, x=’column_name’)

Sample Data for Histogram

We generate a randon sample of normal distribution (mean = 5, SD = 1). Thus, we should expect a bell shape histogram.

import numpy as np
# set sead
np.random.seed(0)
# mean and standard deviation
mu, sigma = 5, 1 
# generate normal distribution data
y = np.random.normal(mu, sigma, 50)
print(y)

Output:

[6.76405235 5.40015721 5.97873798 7.2408932  6.86755799 4.02272212
 5.95008842 4.84864279 4.89678115 5.4105985  5.14404357 6.45427351
 5.76103773 5.12167502 5.44386323 5.33367433 6.49407907 4.79484174
 5.3130677  4.14590426 2.44701018 5.6536186  5.8644362  4.25783498
 7.26975462 3.54563433 5.04575852 4.81281615 6.53277921 6.46935877
 5.15494743 5.37816252 4.11221425 3.01920353 4.65208785 5.15634897
 6.23029068 6.20237985 4.61267318 4.69769725 3.95144703 3.57998206
 3.29372981 6.9507754  4.49034782 4.5619257  3.74720464 5.77749036
 3.38610215 4.78725972]

Example 1: Using matplotlib

We can use the hist() function in Matplotlib to plot a histogram.

# Use hist() in matplotlib to plot the histogram
import matplotlib.pyplot as plt
plt.hist(y,bins='auto') 

Output:

(array([ 2.,  5.,  6., 14., 10.,  8.,  5.]),
 array([2.44701018, 3.13597368, 3.82493717, 4.51390066, 5.20286415,
        5.89182764, 6.58079113, 7.26975462]),
 <a list of 7 Patch objects>)
Histogram in Python (Matplotlib)
Histogram in Python (Matplotlib)

Example 2: Using pandas

We can also use pandas to plot histogram and below is the sample Python code.

# Use hist() in pandas to plot the histogram
import pandas as pd
y=pd.DataFrame(y)
y.hist()

Output:

Histogram in Python (Pandas)
Histogram in Python (Pandas)

Example 3: Use seaborn

# Use histplot() in seaborn to plot the histogram
import seaborn as sns
sns.histplot(data=y, x="y")

Output:

Histogram in Python (seaborn)
Histogram in Python (seaborn)

Further Reading