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

Basic Subplots in Matplotlib

Learn how to create multiple plots inside a single figure using Matplotlib. Understand rows, columns, axes objects and subplot layouts.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand what subplots are in Matplotlib.
  • Create multiple plots inside one figure.
  • Use the plt.subplots() function.
  • Arrange plots using rows and columns.
  • Access individual Axes objects.
  • Customize subplot titles, labels and figure size.
  • Share X-axis and Y-axis between multiple plots.

2. Introduction to Subplots

A subplot is an individual plotting area inside a larger Matplotlib figure. Subplots allow us to display multiple charts together in a single figure.

For example, we can display a line chart, bar chart, scatter plot and histogram together. This makes it easier to compare different datasets and understand relationships between them.

Figure and Axes in Subplots

A Figure is the complete window or canvas. Each Axes object is an individual plotting area inside that figure. A figure can contain one or multiple Axes objects.

Figure Axes 1 Axes 2 Axes 3 Axes 4

One Figure containing four individual Axes objects arranged in a 2 × 2 grid.

3. Using plt.subplots()

The plt.subplots() function is one of the most commonly used ways to create a figure with one or more subplots.

It returns two objects: a Figure object and an Axes object or an array of Axes objects, depending on the number of subplots.

Syntax

fig, ax = plt.subplots(
    nrows=1,
    ncols=1,
    figsize=(width, height)
)
Parameter Description
nrows Number of rows in the subplot grid.
ncols Number of columns in the subplot grid.
figsize Width and height of the complete figure in inches.
sharex Controls sharing of the X-axis between subplots.
sharey Controls sharing of the Y-axis between subplots.

Example: Creating a Single Subplot

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

ax.plot(x, y)

ax.set_title("Simple Line Plot")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

plt.show()

Expected Output

Figure created with one plotting area.

Title: Simple Line Plot
X-axis: X Values
Y-axis: Y Values

A line chart displays the given X and Y values.
Tip: When you create only one subplot, ax is a single Axes object. You can directly call methods such as ax.plot() and ax.set_title().

4. Creating Subplots in One Row

We can create multiple plotting areas horizontally by setting nrows=1 and specifying the required number of columns.

Axes 1 Axes 2 Axes 3

Three subplots arranged horizontally in one row.

Example: 1 Row and 3 Columns

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y1 = [10, 20, 15, 25, 30]
y2 = [5, 15, 10, 20, 25]
y3 = [20, 25, 30, 35, 40]

fig, ax = plt.subplots(1, 3, figsize=(12, 4))

ax[0].plot(x, y1)
ax[0].set_title("Plot 1")

ax[1].plot(x, y2)
ax[1].set_title("Plot 2")

ax[2].plot(x, y3)
ax[2].set_title("Plot 3")

plt.tight_layout()
plt.show()

Expected Output

One figure containing three line charts.

First chart  : Plot 1
Second chart : Plot 2
Third chart  : Plot 3

All three charts appear horizontally in one row.
Remember: When multiple columns are created, ax contains multiple Axes objects. We access them using indexes such as ax[0], ax[1] and ax[2].

5. Creating Subplots with Multiple Rows and Columns

Matplotlib also allows us to create a grid of subplots. We can use multiple rows and columns to organize different charts in one figure.

Plot 1 Plot 2 Plot 3 Plot 4

Four different plotting areas arranged in a 2 × 2 subplot grid.

Example: 2 Rows and 2 Columns

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y1 = [10, 20, 15, 25, 30]
y2 = [5, 15, 10, 20, 25]
y3 = [20, 25, 30, 35, 40]
y4 = [30, 25, 20, 15, 10]

fig, ax = plt.subplots(2, 2, figsize=(10, 7))

ax[0, 0].plot(x, y1)
ax[0, 0].set_title("Line Plot")

ax[0, 1].bar(x, y2)
ax[0, 1].set_title("Bar Chart")

ax[1, 0].scatter(x, y3)
ax[1, 0].set_title("Scatter Plot")

ax[1, 1].plot(x, y4, color="red")
ax[1, 1].set_title("Second Line Plot")

plt.tight_layout()
plt.show()

Expected Output

A single figure containing four charts:

Top-left     : Line Plot
Top-right    : Bar Chart
Bottom-left  : Scatter Plot
Bottom-right : Second Line Plot

Layout: 2 rows × 2 columns
Important: In a 2 × 2 grid, use two indexes to access an Axes object. For example, ax[0, 0] represents the first row and first column.

6. Understanding Axes Indexing

The way we access an Axes object depends on the number of rows and columns created by plt.subplots().

Subplot Layout Axes Access Example
1 × 1 Single Axes object ax.plot()
1 × 3 One-dimensional array ax[0]
3 × 1 One-dimensional array ax[0]
2 × 2 Two-dimensional array ax[0, 0]
3 × 3 Two-dimensional array ax[2, 1]

Example: Accessing Individual Subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)

ax[0, 0].set_title("First Plot")
ax[0, 1].set_title("Second Plot")
ax[1, 0].set_title("Third Plot")
ax[1, 1].set_title("Fourth Plot")

plt.tight_layout()
plt.show()

Expected Output

Four subplot areas with their respective titles:

ax[0, 0] = First Plot
ax[0, 1] = Second Plot
ax[1, 0] = Third Plot
ax[1, 1] = Fourth Plot

7. Setting Figure Size with figsize

The figsize parameter controls the overall width and height of a figure. Its values are measured in inches.

When a figure contains multiple subplots, selecting a suitable figure size helps prevent charts, titles and labels from overlapping.

Example

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    2,
    2,
    figsize=(12, 8)
)

ax[0, 0].set_title("Chart 1")
ax[0, 1].set_title("Chart 2")
ax[1, 0].set_title("Chart 3")
ax[1, 1].set_title("Chart 4")

plt.tight_layout()
plt.show()

Expected Output

Figure dimensions: 12 inches wide × 8 inches high

Layout: 2 rows × 2 columns
Each subplot has sufficient display space.
Tip: Increase the figure width for more columns and increase the figure height for more rows when the charts look crowded.

8. Sharing X-axis and Y-axis

Sometimes multiple subplots display related data. In such cases, sharing the same X-axis or Y-axis makes comparison easier.

Sharing X-axis

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

fig, ax = plt.subplots(
    2,
    1,
    sharex=True
)

ax[0].plot(x, [10, 20, 30, 40, 50])
ax[0].set_title("First Plot")

ax[1].plot(x, [5, 15, 25, 35, 45])
ax[1].set_title("Second Plot")

plt.tight_layout()
plt.show()

Expected Output

Two vertically arranged line charts.

Both charts share the same X-axis scale.
The X-axis values remain consistent between the charts.

Sharing Y-axis

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

fig, ax = plt.subplots(
    1,
    2,
    sharey=True
)

ax[0].plot(x, [10, 20, 30, 40, 50])
ax[0].set_title("First Plot")

ax[1].plot(x, [15, 25, 35, 45, 55])
ax[1].set_title("Second Plot")

plt.tight_layout()
plt.show()

Expected Output

Two horizontally arranged line charts.

Both charts share the same Y-axis scale.
The Y-axis values remain consistent between the charts.
Parameter Purpose
sharex=True Shares the X-axis between subplots.
sharey=True Shares the Y-axis between subplots.
sharex="all" Shares the X-axis across all subplots.
sharey="all" Shares the Y-axis across all subplots.

9. Adding Titles and Labels to Subplots

Each Axes object can have its own title, X-axis label and Y-axis label. We can also add a common title to the complete figure using fig.suptitle().

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

fig, ax = plt.subplots(1, 2, figsize=(10, 4))

ax[0].plot(x, [10, 20, 15, 25, 30])
ax[0].set_title("Sales")
ax[0].set_xlabel("Month")
ax[0].set_ylabel("Sales Amount")

ax[1].bar(x, [5, 10, 15, 20, 25])
ax[1].set_title("Profit")
ax[1].set_xlabel("Month")
ax[1].set_ylabel("Profit Amount")

fig.suptitle("Business Performance")

plt.tight_layout()
plt.show()

Expected Output

Common Figure Title: Business Performance

Left subplot:
Title: Sales
X-axis: Month
Y-axis: Sales Amount

Right subplot:
Title: Profit
X-axis: Month
Y-axis: Profit Amount

10. Managing Subplot Spacing

When multiple charts are placed together, titles and labels may overlap. Matplotlib provides layout functions to manage spacing.

Using tight_layout()

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize=(10, 7))

ax[0, 0].set_title("First Chart")
ax[0, 1].set_title("Second Chart")
ax[1, 0].set_title("Third Chart")
ax[1, 1].set_title("Fourth Chart")

plt.tight_layout()
plt.show()

Expected Output

Four subplots are arranged with adjusted spacing.
Titles and axis labels have more room.
Overlapping between subplot elements is reduced.

Using constrained_layout

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    2,
    2,
    figsize=(10, 7),
    layout="constrained"
)

ax[0, 0].set_title("First Chart")
ax[0, 1].set_title("Second Chart")
ax[1, 0].set_title("Third Chart")
ax[1, 1].set_title("Fourth Chart")

plt.show()

Expected Output

A 2 × 2 subplot figure with automatically managed layout spacing.
Important: Avoid combining plt.tight_layout() and constrained layout unnecessarily. Choose the layout approach that suits your figure.

11. Difference Between subplot() and subplots()

Matplotlib provides both plt.subplot() and plt.subplots(). Their names are similar, but their usage is different.

Feature plt.subplot() plt.subplots()
Purpose Adds or selects a subplot in a grid. Creates a figure and a collection of subplots.
Return value Returns an Axes object. Returns a Figure and Axes object or array.
Usage Creates/selects individual subplot areas. Convenient for creating multiple subplots together.
Example plt.subplot(2, 2, 1) plt.subplots(2, 2)

Example Using plt.subplot()

import matplotlib.pyplot as plt

plt.subplot(2, 1, 1)
plt.plot([1, 2, 3], [10, 20, 30])
plt.title("First Plot")

plt.subplot(2, 1, 2)
plt.plot([1, 2, 3], [30, 20, 10])
plt.title("Second Plot")

plt.tight_layout()
plt.show()

Expected Output

Two vertically arranged plots.

First subplot  : First Plot
Second subplot : Second Plot

12. Practical Example: Student Performance Dashboard

Let's create a simple student performance dashboard using four different charts. Each chart will display a different aspect of student performance.

Complete Python Program

import matplotlib.pyplot as plt

students = ["Amit", "Rahul", "Priya", "Sneha", "Rohit"]

marks = [85, 75, 90, 80, 70]
attendance = [90, 85, 95, 80, 75]
study_hours = [5, 4, 6, 5, 3]
projects = [4, 3, 5, 4, 2]

fig, ax = plt.subplots(2, 2, figsize=(12, 8))

# Marks chart
ax[0, 0].bar(students, marks, color="skyblue")
ax[0, 0].set_title("Student Marks")
ax[0, 0].set_ylabel("Marks")

# Attendance chart
ax[0, 1].plot(
    students,
    attendance,
    marker="o",
    color="green"
)
ax[0, 1].set_title("Student Attendance")
ax[0, 1].set_ylabel("Attendance (%)")

# Study hours chart
ax[1, 0].scatter(
    students,
    study_hours,
    color="red"
)
ax[1, 0].set_title("Study Hours")
ax[1, 0].set_ylabel("Hours")

# Projects chart
ax[1, 1].bar(
    students,
    projects,
    color="orange"
)
ax[1, 1].set_title("Completed Projects")
ax[1, 1].set_ylabel("Projects")

fig.suptitle("Student Performance Dashboard")

plt.tight_layout()
plt.show()

Expected Output

Student Performance Dashboard

Top-left:
Student Marks - Bar Chart

Top-right:
Student Attendance - Line Chart

Bottom-left:
Study Hours - Scatter Plot

Bottom-right:
Completed Projects - Bar Chart

All four charts appear inside one figure.
Real-world use: Subplots are useful for dashboards, data analysis reports, business comparisons, student performance analysis and scientific visualization.

13. Common Mistakes While Creating Subplots

1. Using the Wrong Index

For a 2 × 2 subplot grid, use two-dimensional indexing such as ax[0, 0]. Do not use ax[0] when you need to select an individual cell.

2. Confusing Figure and Axes

The Figure represents the complete canvas, while Axes represents an individual plotting area. Use fig.suptitle() for a common figure title and ax.set_title() for an individual subplot title.

3. Overlapping Titles and Labels

When subplot spacing is insufficient, labels and titles can overlap. Use plt.tight_layout() or constrained layout to improve the arrangement.

4. Incorrect Figure Size

A small figure with many subplots may look crowded. Select a suitable figsize based on the number of rows and columns.

14. Practice Questions

  1. What are subplots in Matplotlib?
  2. What is the purpose of plt.subplots()?
  3. What is the difference between Figure and Axes?
  4. How do you create a subplot layout with 2 rows and 3 columns?
  5. How do you access the second subplot in a 1 × 3 layout?
  6. What is the purpose of the figsize parameter?
  7. How do you share the X-axis between multiple subplots?
  8. What is the difference between plt.subplot() and plt.subplots()?
  9. How do you add a common title to the complete figure?
  10. Why do we use plt.tight_layout()?

Summary

Subplots allow us to display multiple charts inside a single Matplotlib figure. They are useful when we need to compare different datasets or visualize multiple aspects of the same data.

The plt.subplots() function creates a Figure object and one or more Axes objects. We can specify the number of rows and columns to organize the plotting areas in different layouts.

We can access individual Axes objects using indexes, customize each subplot with titles and labels, and control the overall figure size using the figsize parameter.

Parameters such as sharex and sharey help maintain common axis scales. Functions such as plt.tight_layout() and constrained layout help manage spacing between subplot elements.

Understanding basic subplots provides a strong foundation for creating organized dashboards, reports and advanced Matplotlib visualizations.