Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Histograms in Matplotlib

In this lesson, you will learn how to create histograms using Matplotlib. You will understand data distributions, bins, frequency, density, cumulative histograms, and histogram customization.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand what a histogram is and where it is used.
  • Create histograms using the hist() function.
  • Understand bins, frequency, and data intervals.
  • Customize histogram colours and borders.
  • Control the number and width of bins.
  • Create density and cumulative histograms.
  • Compare multiple data distributions.
  • Add titles, labels, legends, and grid lines.
  • Save histograms in different file formats.

2. What Is a Histogram?

A histogram is a graphical representation that shows the distribution of numerical data. It divides data into intervals called bins and displays the frequency of values within each interval.

In Matplotlib, the hist() function is used to create histograms. Each bar represents an interval, and its height represents the number of observations in that interval.

Example: Student Exam Marks

Suppose a teacher wants to understand how students performed in an examination. Instead of displaying every student's marks separately, the teacher can group the marks into intervals such as 0–20, 20–40, 40–60, 60–80, and 80–100.

Distribution of Student Exam Marks 5 15 22 17 7 0–20 20–40 40–60 60–80 80–100 Frequency Exam Marks
Figure 1: A histogram showing the distribution of student exam marks.

3. Basic Syntax of the hist() Function

The hist() function accepts numerical data and groups the values into intervals called bins.

Syntax

import matplotlib.pyplot as plt

plt.hist(data)

plt.show()
Parameter Description
data Numerical values used to create the histogram.
plt.hist() Creates a histogram from numerical data.
plt.show() Displays the created histogram.
Tip: Histograms are mainly used with numerical data. They help you understand how values are distributed.

4. Creating Your First Histogram

Let's create a histogram to understand the distribution of students' examination marks.

Example: Student Exam Marks

import matplotlib.pyplot as plt

marks = [
    35, 40, 45, 50, 55,
    60, 65, 70, 75, 80,
    85, 90, 55, 65, 75,
    45, 50, 60, 70, 80
]

plt.hist(marks)

plt.title("Distribution of Student Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")

plt.show()

Explanation:

  • marks contains the examination marks of students.
  • hist() groups the marks into intervals.
  • The X-axis displays the mark intervals.
  • The Y-axis displays the frequency of observations.
  • title(), xlabel(), and ylabel() add chart information.
  • show() displays the histogram.
Distribution of Student Marks 2 6 8 6 2 30–42 42–54 54–66 66–78 78–90 Frequency
Figure 2: Expected histogram output for the student marks example.

5. Understanding Bins in a Histogram

Bins are intervals used to group numerical data. Each bin represents a range of values, and its height shows how many observations fall within that range.

Example: Changing the Number of Bins

import matplotlib.pyplot as plt

marks = [
    35, 40, 45, 50, 55,
    60, 65, 70, 75, 80,
    85, 90, 55, 65, 75,
    45, 50, 60, 70, 80
]

plt.hist(marks, bins=5, color="skyblue",
         edgecolor="black")

plt.title("Histogram with 5 Bins")
plt.xlabel("Marks")
plt.ylabel("Frequency")

plt.show()
Bins Description
bins=5 Divides the data range into five intervals.
bins=10 Divides the data range into ten intervals.
bins=20 Divides the data range into twenty intervals.
Histogram with 5 Bins 2 6 8 6 2 Bin 1 Bin 2 Bin 3 Bin 4 Bin 5
Figure 3: The data is divided into five intervals.

6. Customizing Histogram Colours and Borders

You can customize a histogram using parameters such as color, edgecolor, alpha, and linewidth.

Example: Customized Histogram

import matplotlib.pyplot as plt

marks = [
    35, 40, 45, 50, 55,
    60, 65, 70, 75, 80,
    85, 90, 55, 65, 75,
    45, 50, 60, 70, 80
]

plt.hist(
    marks,
    bins=6,
    color="mediumseagreen",
    edgecolor="black",
    alpha=0.8,
    linewidth=1.5
)

plt.title("Customized Student Marks Histogram")
plt.xlabel("Marks")
plt.ylabel("Frequency")

plt.show()
Parameter Description Example
color Sets the fill colour of histogram bars. color="green"
edgecolor Sets the border colour of bars. edgecolor="black"
alpha Controls transparency. alpha=0.8
linewidth Controls the border thickness. linewidth=1.5
Customized Student Marks Histogram Bin 1 Bin 2 Bin 3 Bin 4 Bin 5 Bin 6
Figure 4: A green histogram with black borders.

7. Understanding Frequency and Density

A frequency histogram displays the number of observations in each bin. A density histogram displays normalized values so that the total area under the histogram is equal to one.

Example: Density Histogram

import matplotlib.pyplot as plt

marks = [
    35, 40, 45, 50, 55,
    60, 65, 70, 75, 80,
    85, 90, 55, 65, 75,
    45, 50, 60, 70, 80
]

plt.hist(
    marks,
    bins=5,
    density=True,
    color="orange",
    edgecolor="black"
)

plt.title("Density Histogram")
plt.xlabel("Marks")
plt.ylabel("Density")

plt.show()
Tip: Use density=True when you want to compare distributions on a normalized scale rather than compare raw counts.
Density Histogram 30–42 42–54 54–66 66–78 78–90
Figure 5: A representative density histogram showing a normalized distribution.

8. Creating a Cumulative Histogram

A cumulative histogram displays the running total of observations as you move from one bin to the next. It helps understand how many values fall below a particular point.

Example: Cumulative Student Marks

import matplotlib.pyplot as plt

marks = [
    35, 40, 45, 50, 55,
    60, 65, 70, 75, 80,
    85, 90, 55, 65, 75,
    45, 50, 60, 70, 80
]

plt.hist(
    marks,
    bins=5,
    cumulative=True,
    color="cornflowerblue",
    edgecolor="black"
)

plt.title("Cumulative Histogram")
plt.xlabel("Marks")
plt.ylabel("Cumulative Frequency")

plt.show()

The cumulative=True parameter adds each bin's frequency to the total from the previous bins.

Cumulative Histogram Bin 1 Bin 2 Bin 3 Bin 4 Bin 5
Figure 6: The cumulative frequency increases from left to right.

9. Comparing Multiple Histograms

You can compare two or more data distributions by plotting multiple histograms in the same chart. Transparency helps identify overlapping intervals.

Example: Comparing Marks of Two Classes

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75, 80]
class_b = [50, 55, 60, 65, 70, 75, 80, 85]

plt.hist(
    class_a,
    bins=5,
    alpha=0.6,
    color="blue",
    label="Class A"
)

plt.hist(
    class_b,
    bins=5,
    alpha=0.6,
    color="orange",
    label="Class B"
)

plt.title("Comparison of Class Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.legend()

plt.show()
Tip: Use alpha to make overlapping histogram bars easier to distinguish.
Comparison of Class Marks Class A Class B
Figure 7: Two overlapping histograms compare the marks of two classes.

10. Adding Titles, Labels, and Grid Lines

Titles and labels explain the information displayed in a histogram. Grid lines make it easier to estimate frequencies.

Function Purpose
plt.title()Adds a chart title.
plt.xlabel()Adds the X-axis label.
plt.ylabel()Adds the Y-axis label.
plt.grid()Displays grid lines.
plt.legend()Displays labels for data groups.

Example: Formatted Histogram

import matplotlib.pyplot as plt

ages = [
    18, 20, 22, 25, 27, 30,
    32, 35, 37, 40, 42, 45,
    25, 28, 30, 33, 36, 39
]

plt.hist(
    ages,
    bins=6,
    color="purple",
    edgecolor="black",
    label="People"
)

plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")

plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.legend()

plt.show()
Age Distribution 18–22 22–26 26–30 30–34 34–38 38–42 People
Figure 8: A formatted histogram with a title, axis labels, grid lines, and legend.

11. Histogram vs Bar Chart

Histograms and bar charts look similar, but they are used for different purposes. A histogram displays the distribution of numerical data, while a bar chart compares categories.

Histogram Bar Chart Continuous intervals Separate categories
Figure 9: Histograms display continuous intervals; bar charts compare separate categories.
Feature Histogram Bar Chart
Data Type Continuous numerical data. Categorical data.
Bars Usually touch each other. Usually have gaps.
Purpose Shows data distribution. Compares category values.
Matplotlib Function plt.hist() plt.bar()

12. Saving a Histogram

You can save a histogram using the savefig() function. Matplotlib supports formats such as PNG, JPEG, SVG, and PDF.

Example: Saving a Histogram

import matplotlib.pyplot as plt

marks = [35, 40, 45, 50, 55, 60, 65, 70, 75, 80]

plt.hist(
    marks,
    bins=5,
    color="skyblue",
    edgecolor="black"
)

plt.title("Student Marks Histogram")

plt.savefig(
    "student_histogram.png",
    dpi=300,
    bbox_inches="tight"
)

plt.show()
Parameter Description
student_histogram.png Name and format of the saved histogram.
dpi=300 Sets the output resolution.
bbox_inches="tight" Adjusts the saved bounding box to fit the chart content.
Important: Save the figure before calling plt.show() when using workflows where displaying the figure may close or clear it.
Student Marks Histogram 30–42 42–54 54–66 66–78 78–90
Figure 10: Example appearance of the saved student_histogram.png file.

13. Common Mistakes While Creating Histograms

Beginners may face common problems while creating histograms. Understanding these issues helps you write correct Matplotlib code.

Common Mistake Solution
Using categorical text data in hist(). Use numerical data to create a histogram.
Too many bins make the chart difficult to read. Choose a suitable number of bins.
Too few bins hide important details. Increase the number of bins when necessary.
Histogram bars are difficult to distinguish. Use edgecolor to add borders.
Overlapping distributions are difficult to compare. Use alpha to add transparency.
Chart is not displayed. Call plt.show() in a normal Python script.

14. Practical Activity

Task: Create an Employee Age Distribution Histogram

Create a histogram to understand the age distribution of employees in a company.

  1. Create a list containing employee ages.
  2. Use plt.hist() to create a histogram.
  3. Set the number of bins to 6.
  4. Set the bar colour to green.
  5. Add black borders to the bars.
  6. Add a chart title and axis labels.
  7. Enable grid lines.
  8. Save the chart as employee_age_distribution.png.

Starter Code

import matplotlib.pyplot as plt

employee_ages = [
    22, 25, 28, 30, 32, 35,
    38, 40, 42, 45, 27, 33,
    36, 39, 41, 29, 31, 44
]

# Create your histogram here

plt.show()

15. Practice Questions

Test your understanding of Matplotlib histograms:

  1. What is a histogram?
  2. Which Matplotlib function creates a histogram?
  3. What is a bin in a histogram?
  4. What does the height of a histogram bar represent?
  5. Which parameter controls the number of bins?
  6. What is the purpose of the density parameter?
  7. What does cumulative=True do?
  8. How can you change the colour of histogram bars?
  9. What is the difference between a histogram and a bar chart?
  10. Which function is used to save a histogram?

Summary

In this lesson, you learned how to create histograms using Matplotlib. You explored the hist() function, bins, frequency, density, cumulative histograms, multiple distributions, and chart formatting.

  • Use plt.hist() to create histograms.
  • Use bins to divide numerical data into intervals.
  • Use color to customize histogram bars.
  • Use edgecolor to set bar borders.
  • Use alpha to control transparency.
  • Use density=True to create a normalized histogram.
  • Use cumulative=True to display cumulative frequency.
  • Use title(), xlabel(), and ylabel() to describe the chart.
  • Use legend() to identify different data groups.
  • Use savefig() to save the histogram.

You are now ready to create histograms and understand numerical data distributions using Matplotlib.