0
0
Matplotlibdata~5 mins

Basic histogram with plt.hist in Matplotlib

Choose your learning style9 modes available
Introduction

A histogram helps us see how data is spread out by showing how many values fall into different groups.

To understand the distribution of exam scores in a class.
To see how daily temperatures vary over a month.
To check the frequency of different ages in a group of people.
To analyze how often certain sales amounts occur in a store.
Syntax
Matplotlib
plt.hist(data, bins=number_of_bins, color='color_name', edgecolor='color_name')

data is the list or array of numbers you want to plot.

bins controls how many groups the data is split into.

Examples
Simple histogram with default bins.
Matplotlib
plt.hist([1, 2, 2, 3, 3, 3, 4])
Histogram with 5 bins to group data more finely.
Matplotlib
plt.hist(data, bins=5)
Histogram with 4 bins and colors for better look.
Matplotlib
plt.hist(data, bins=4, color='skyblue', edgecolor='black')
Sample Program

This code shows how ages are spread in 5 groups. The bars show how many people fall in each age group.

Matplotlib
import matplotlib.pyplot as plt

# Sample data: ages of 15 people
ages = [22, 25, 27, 30, 22, 24, 29, 31, 35, 30, 28, 26, 27, 29, 30]

# Create histogram with 5 bins
plt.hist(ages, bins=5, color='lightgreen', edgecolor='black')

# Add title and labels
plt.title('Age Distribution')
plt.xlabel('Age groups')
plt.ylabel('Number of people')

# Show the plot
plt.show()
OutputSuccess
Important Notes

If you don't set bins, matplotlib chooses a default number.

Adding edgecolor helps see the bars clearly.

Histograms work best with numeric data.

Summary

A histogram groups data into bins and shows how many values fall in each.

Use plt.hist() with your data and choose bins to control grouping.

Colors and labels make the chart easier to understand.