Plot a Histogram in Python Using Matplotlib

When I first started working with data in Python more than a decade ago, one of the first visualizations I learned was the histogram.

In my projects, especially when analyzing survey results or financial data from U.S. clients, histograms became my go-to tool. They helped me quickly identify trends, outliers, and the overall shape of the data.

In this tutorial, I will show you how to plot a histogram in Python using Matplotlib. I’ll walk you through step-by-step methods, share full code examples, and explain how you can customize your plots for professional use.

What is a Histogram?

A histogram is a type of bar chart that shows the frequency distribution of a dataset.

Instead of plotting individual data points, it groups values into bins and displays the number of values that fall into each bin.

This makes it perfect for understanding the spread of data, whether it’s exam scores, household incomes, or product sales in the U.S. market.

Method 1 – Plot a Simple Histogram

The first method I use is the basic plt.hist() function from Matplotlib. This is the simplest way to create a histogram and is ideal when you want to quickly understand your data.

import matplotlib.pyplot as plt
import numpy as np

# Example dataset: Monthly household income in USD (sampled data)
income_data = [4200, 4800, 5000, 5200, 5300, 5400, 5500, 5600, 5700, 
               6000, 6100, 6200, 6500, 7000, 7200, 7500, 8000, 8200, 
               8500, 9000, 9500, 10000, 11000, 12000]

# Plot histogram
plt.hist(income_data, bins=10, color='skyblue', edgecolor='black')

# Add labels and title
plt.xlabel("Monthly Income (USD)")
plt.ylabel("Number of Households")
plt.title("Distribution of Monthly Household Income in the USA")

# Show plot
plt.show()

I executed the above example code and added the screenshot below.

Histogram in Python using Matplotlib

This code plots a histogram of household income data. The bins divide the income ranges, and the height of each bar shows how many households fall into that range.

Method 2 – Customize the Number of Bins

Sometimes, the default number of bins doesn’t give you the best view of your data. I often adjust the number of bins to make the distribution clearer.

import matplotlib.pyplot as plt

# Same dataset as before
income_data = [4200, 4800, 5000, 5200, 5300, 5400, 5500, 5600, 5700, 
               6000, 6100, 6200, 6500, 7000, 7200, 7500, 8000, 8200, 
               8500, 9000, 9500, 10000, 11000, 12000]

# Plot histogram with custom bins
plt.hist(income_data, bins=5, color='orange', edgecolor='black')

# Add labels and title
plt.xlabel("Monthly Income (USD)")
plt.ylabel("Number of Households")
plt.title("Household Income Distribution (5 Bins)")

plt.show()

I executed the above example code and added the screenshot below.

Plot a Histogram using Matplotlib

By reducing the bins to 5, we get a broader view of the income distribution. This is useful when presenting data to non-technical stakeholders who prefer simpler visuals.

Method 3 – Add Gridlines and Styling

I often add gridlines and style elements to make histograms more professional. This helps when I share reports with clients or colleagues.

import matplotlib.pyplot as plt

# Dataset: Employee ages in a U.S. company
ages = [22, 25, 27, 29, 30, 32, 35, 36, 37, 38, 40, 42, 45, 46, 48, 
        50, 52, 55, 57, 60, 62, 65]

plt.hist(ages, bins=8, color='green', edgecolor='black', alpha=0.7)

plt.xlabel("Age")
plt.ylabel("Number of Employees")
plt.title("Age Distribution of Employees in a U.S. Company")

# Add gridlines
plt.grid(axis='y', linestyle='--', alpha=0.7)

plt.show()

I executed the above example code and added the screenshot below.

Plot a Histogram in Python using Matplotlib

The gridlines make it easier to read the values, especially when presenting to a larger audience. I also adjusted the transparency (alpha) to make the plot visually appealing.

Method 4 – Plot Multiple Histograms

In real-world projects, I often need to compare two datasets side by side. For example, comparing male and female employee age distributions in a company.

import matplotlib.pyplot as plt

# Sample datasets
male_ages = [22, 25, 27, 29, 30, 35, 36, 38, 40, 42, 45, 50, 52, 55, 60]
female_ages = [23, 26, 28, 31, 33, 37, 39, 41, 44, 47, 49, 53, 56, 58, 62]

plt.hist([male_ages, female_ages], bins=8, label=['Male', 'Female'], 
         color=['blue', 'pink'], edgecolor='black')

plt.xlabel("Age")
plt.ylabel("Number of Employees")
plt.title("Age Distribution by Gender in a U.S. Company")

plt.legend()
plt.show()

I executed the above example code and added the screenshot below.

Histogram in Python Matplotlib

This method is great for visual comparisons. The overlapping histograms show how distributions differ between groups.

Method 5 – Normalized Histograms (Density Plot)

Sometimes, I want to see the probability distribution instead of raw counts. This is where normalized histograms (density plots) are useful.

import matplotlib.pyplot as plt
import numpy as np

# Dataset: Test scores of students in the USA
scores = np.random.normal(75, 10, 200)  # Mean=75, Std=10, n=200

plt.hist(scores, bins=10, density=True, color='purple', edgecolor='black', alpha=0.7)

plt.xlabel("Test Scores")
plt.ylabel("Probability Density")
plt.title("Distribution of Student Test Scores in the USA")

plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

Here, the histogram shows the probability density instead of counts. This is especially useful in statistics and machine learning projects.

Method 6 – Add a Best Fit Line

I often overlay a normal distribution curve on top of a histogram. This helps me check if the data follows a normal distribution.

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm

# Dataset: SAT scores in the USA
scores = np.random.normal(1050, 200, 300)  # Mean=1050, Std=200, n=300

# Plot histogram
count, bins, ignored = plt.hist(scores, bins=15, density=True, color='lightblue', edgecolor='black')

# Plot normal distribution curve
mu, sigma = 1050, 200
plt.plot(bins, norm.pdf(bins, mu, sigma), 'r--')

plt.xlabel("SAT Scores")
plt.ylabel("Probability Density")
plt.title("Distribution of SAT Scores in the USA with Normal Fit")

plt.show()

The red dashed line represents the normal distribution curve. This method is widely used in statistical analysis and reporting.

Method 7 – Horizontal Histograms

Sometimes, I prefer horizontal histograms for better readability. This is especially useful when the category labels are long.

import matplotlib.pyplot as plt

# Dataset: Weekly working hours of employees
hours = [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 52, 55]

plt.hist(hours, bins=8, orientation='horizontal', color='teal', edgecolor='black')

plt.xlabel("Number of Employees")
plt.ylabel("Working Hours per Week")
plt.title("Distribution of Weekly Working Hours in the USA")

plt.show()

The horizontal layout makes it easier to compare values across bins. I use this when presenting employee-related data to HR teams.

Key Takeaways

  • Use plt.hist() for quick histograms.
  • Adjust bins for clarity depending on your audience.
  • Add gridlines, labels, and colors to make your plots professional.
  • Compare multiple datasets with overlapping histograms.
  • Use density plots and best-fit lines for statistical insights.
  • Experiment with horizontal histograms for better readability.

Histograms are one of the most versatile tools in data visualization. With Matplotlib, you can create them quickly, customize them easily, and apply them to real-world datasets.

Whether you’re analyzing household income, employee ages, or student test scores in the U.S., histograms give you a clear picture of your data.

I hope you found this tutorial helpful. Try these methods on your own datasets and see how they reveal insights you might have missed before.

You may read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.