Saturday , December 5 2026
Histogram using Matplotlib

Histogram using Matplotlib

Updated: 28 November 2026Level: BeginnerReading time: about 7 minutesMatplotlib 3.8+

A histogram shows the distribution of a numeric variable: how many values fall into each range (bin). It answers questions like “Are most students scoring between 60 and 80?” and helps spot skew and outliers before modelling.

Prerequisites

Introduction to Matplotlib.

Basic Histogram

Example
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
marks = rng.normal(65, 12, 500).clip(0, 100)

fig, ax = plt.subplots()
ax.hist(marks, bins=20, color='skyblue', edgecolor='black')
ax.set_xlabel('Marks')
ax.set_ylabel('Number of students')
plt.show()

Explanation: The range of marks is split into 20 equal bins and each bar’s height is the count in that bin. The shape here is a bell curve because the data comes from a normal distribution.

Choosing Bins

Example
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
for ax, b in zip(axes, [5, 20, 60]):
    ax.hist(marks, bins=b)
    ax.set_title(f'bins={b}')
plt.show()

Explanation: Too few bins hide detail; too many make the chart noisy. You can also pass edges like bins=[0, 40, 60, 80, 100] or bins='auto'.

Compare Two Groups

Example
a = rng.normal(60, 10, 300)
b = rng.normal(72, 8, 300)
fig, ax = plt.subplots()
ax.hist(a, bins=25, alpha=0.5, label='Batch A')
ax.hist(b, bins=25, alpha=0.5, label='Batch B')
ax.legend()
plt.show()

Density and Cumulative

Example
fig, ax = plt.subplots()
ax.hist(marks, bins=20, density=True)
ax.hist(marks, bins=20, density=True, cumulative=True, histtype='step')
plt.show()

Explanation: density=True scales bars so the area is 1 (a probability density). cumulative shows the running total.

Get the Counts

Example
counts, edges, _ = ax.hist(marks, bins=5)
print(counts, edges.round(1))

Practice Exercises

  1. Plot the distribution of 1000 dice-roll sums (two dice).
  2. Compare histograms of male and female heights.

Interview Questions

Q: Bar chart vs histogram?
Bar charts compare categories; histograms show the distribution of continuous data in bins.

Summary

Use ax.hist with sensible bins, alpha for overlapping groups, and density/cumulative for probability views.

Next: Subplots

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.