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

Advanced Grids in Matplotlib

Learn how to create complex subplot arrangements using GridSpec, subplot_mosaic(), nested grids and spanning layouts. Build flexible figures with different subplot sizes and positions.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand advanced subplot grid arrangements.
  • Use the GridSpec class to create flexible layouts.
  • Control subplot sizes using width_ratios and height_ratios.
  • Create subplots that span multiple rows or columns.
  • Use subplot_mosaic() to create named subplot layouts.
  • Create nested grids using subgridspec().
  • Use Figure.add_subplot() with GridSpec objects.
  • Build dashboard-style visualizations with different chart sizes.

2. Introduction to Advanced Grids

Basic subplot layouts arrange charts in equal-sized rows and columns. However, some visualizations require more flexible arrangements. For example, a dashboard may contain one large chart on the left and two smaller charts on the right.

Matplotlib provides advanced grid tools that allow us to control subplot positions, sizes and arrangements. These tools help us create complex figures without manually calculating every position.

Why Do We Need Advanced Grids?

Advanced grids are useful when all charts do not need the same size. We can make one subplot larger, allow another subplot to occupy multiple rows or columns, and even create smaller grids inside an existing subplot area.

Large Chart Small Chart 1 Small Chart 2

Example of an advanced grid with one large subplot and two smaller subplots.

3. Introduction to GridSpec

GridSpec is a Matplotlib class that defines a grid structure for arranging subplots. It allows us to divide a figure into rows and columns and select specific grid cells for individual Axes objects.

Unlike a basic plt.subplots() layout, GridSpec gives us more control over subplot positions and sizes.

Importing GridSpec

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

Basic Syntax

fig = plt.figure()

gs = GridSpec(
    nrows,
    ncols,
    figure=fig
)
Parameter Description
nrows Number of rows in the grid.
ncols Number of columns in the grid.
figure Figure object associated with the GridSpec layout.
width_ratios Controls relative widths of grid columns.
height_ratios Controls relative heights of grid rows.

Example: Creating a Basic GridSpec

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(9, 6))

gs = GridSpec(
    2,
    2,
    figure=fig
)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

ax1.set_title("Chart 1")
ax2.set_title("Chart 2")
ax3.set_title("Chart 3")
ax4.set_title("Chart 4")

plt.show()

Expected Output

A figure containing four subplot areas.

Grid layout: 2 rows × 2 columns

Chart 1 | Chart 2
Chart 3 | Chart 4

Each subplot is created using fig.add_subplot().
Remember: GridSpec defines the grid, while fig.add_subplot() creates an Axes object in a selected grid position.

4. Selecting Grid Positions with GridSpec

GridSpec supports indexing similar to NumPy arrays. We can select individual cells or ranges of rows and columns using slicing.

Example: Selecting Individual Cells

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(9, 6))

gs = GridSpec(2, 3, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[0, 2])
ax4 = fig.add_subplot(gs[1, 0])
ax5 = fig.add_subplot(gs[1, 1])
ax6 = fig.add_subplot(gs[1, 2])

for i, ax in enumerate(fig.axes):
    ax.set_title(f"Plot {i + 1}")

plt.tight_layout()
plt.show()

Expected Output

Six subplot areas arranged in a 2 × 3 grid.

Top row:
Plot 1 | Plot 2 | Plot 3

Bottom row:
Plot 4 | Plot 5 | Plot 6

Understanding Grid Indexes

gs[0, 0] gs[0, 1] gs[0, 2] gs[1, 0] gs[1, 1] gs[1, 2]

A 2 × 3 GridSpec layout with individual row and column positions.

5. Creating Subplots That Span Multiple Rows or Columns

One of the most useful features of GridSpec is subplot spanning. A single Axes object can occupy multiple grid cells by using Python slicing.

For example, gs[:, 0] selects all rows in the first column, while gs[0, :] selects all columns in the first row.

Example: One Large Subplot and Two Small Subplots

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 6))

gs = GridSpec(2, 2, figure=fig)

# Left subplot spans both rows
ax1 = fig.add_subplot(gs[:, 0])

# Right subplots occupy separate rows
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])

ax1.plot([1, 2, 3, 4], [10, 20, 30, 40])
ax1.set_title("Large Plot")

ax2.bar([1, 2, 3], [10, 20, 30])
ax2.set_title("Top Plot")

ax3.scatter([1, 2, 3], [30, 20, 10])
ax3.set_title("Bottom Plot")

plt.tight_layout()
plt.show()

Expected Output

One figure with three subplot areas.

Left side:
One large chart spanning two rows.

Right side:
Top small chart.
Bottom small chart.
gs[:, 0] gs[0, 1] gs[1, 1]

A large subplot spans both rows on the left, while two smaller plots occupy the right.

Example: One Subplot Spanning Multiple Columns

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 6))

gs = GridSpec(2, 3, figure=fig)

ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[1, 1])
ax4 = fig.add_subplot(gs[1, 2])

ax1.set_title("Wide Main Chart")
ax2.set_title("Chart 2")
ax3.set_title("Chart 3")
ax4.set_title("Chart 4")

plt.tight_layout()
plt.show()

Expected Output

Top row:
One wide chart spanning all three columns.

Bottom row:
Three separate subplot areas.

The main chart uses gs[0, :].

6. Controlling Grid Sizes with Ratios

GridSpec provides width_ratios and height_ratios to control the relative sizes of columns and rows.

These parameters are useful when some charts need more space than others. The values represent relative proportions, not fixed pixel dimensions.

Using width_ratios

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 5))

gs = GridSpec(
    1,
    2,
    figure=fig,
    width_ratios=[2, 1]
)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])

ax1.set_title("Wide Chart")
ax2.set_title("Narrow Chart")

plt.show()

Expected Output

Two horizontally arranged subplots.

First subplot width ratio  : 2
Second subplot width ratio : 1

The first subplot receives approximately twice
the grid width of the second subplot.
Width Ratio 2 Width Ratio 1

width_ratios=[2, 1] gives the first column twice the relative width of the second.

Using height_ratios

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(8, 7))

gs = GridSpec(
    2,
    1,
    figure=fig,
    height_ratios=[2, 1]
)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])

ax1.set_title("Tall Chart")
ax2.set_title("Short Chart")

plt.show()

Expected Output

Two vertically arranged subplots.

First subplot height ratio  : 2
Second subplot height ratio : 1

The first subplot receives approximately twice
the grid height of the second subplot.
Tip: Use width ratios for horizontal layout differences and height ratios for vertical layout differences.

7. Creating Layouts with subplot_mosaic()

The subplot_mosaic() function creates subplot layouts using a visual arrangement of labels. Instead of manually selecting GridSpec indexes, we define a layout using strings or nested lists.

Each unique label represents an Axes object. Repeating a label allows one subplot to span multiple grid positions.

Basic Syntax

fig, ax = plt.subplot_mosaic(
    [
        ["A", "B"],
        ["C", "D"]
    ]
)

Example: Four Subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplot_mosaic([
    ["A", "B"],
    ["C", "D"]
])

ax["A"].plot([1, 2, 3], [10, 20, 30])
ax["A"].set_title("Line Chart")

ax["B"].bar([1, 2, 3], [20, 30, 40])
ax["B"].set_title("Bar Chart")

ax["C"].scatter([1, 2, 3], [30, 20, 10])
ax["C"].set_title("Scatter Plot")

ax["D"].hist([10, 20, 20, 30, 30, 30])
ax["D"].set_title("Histogram")

plt.tight_layout()
plt.show()

Expected Output

Four subplots arranged in a 2 × 2 layout.

A = Line Chart
B = Bar Chart
C = Scatter Plot
D = Histogram

Each Axes object is accessed using its label.
A B C D

A subplot_mosaic layout where labels identify individual Axes objects.

Example: A Subplot Spanning Two Columns

import matplotlib.pyplot as plt

fig, ax = plt.subplot_mosaic([
    ["A", "A", "B"],
    ["C", "D", "B"]
])

ax["A"].set_title("Wide Chart")
ax["B"].set_title("Tall Chart")
ax["C"].set_title("Chart C")
ax["D"].set_title("Chart D")

plt.tight_layout()
plt.show()

Expected Output

Advanced mosaic layout:

A occupies the first row and first two columns.
B occupies the right column across both rows.
C occupies the bottom-left position.
D occupies the bottom-middle position.
Tip: Use meaningful labels such as "sales", "profit" and "customers" instead of single letters when building larger dashboards.

8. Creating Nested Grids with subgridspec()

Nested grids allow us to create a smaller subplot grid inside a particular region of a larger grid. This is useful when a figure contains different sections with their own subplot arrangements.

We can create a nested grid by calling subgridspec() on a selected GridSpec region.

Example

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 7))

gs = GridSpec(1, 2, figure=fig)

# Left side contains one Axes
ax1 = fig.add_subplot(gs[0, 0])
ax1.set_title("Main Chart")

# Right side contains a nested grid
right_grid = gs[0, 1].subgridspec(2, 1)

ax2 = fig.add_subplot(right_grid[0, 0])
ax3 = fig.add_subplot(right_grid[1, 0])

ax2.set_title("Top Right Chart")
ax3.set_title("Bottom Right Chart")

plt.tight_layout()
plt.show()

Expected Output

One figure containing three subplot areas.

Left side:
One main chart.

Right side:
One nested grid with two vertically arranged charts.
Main Chart Nested Chart 1 Nested Chart 2

A nested grid inside the right-hand section of a larger figure.

9. Using GridSpecFromSubplotSpec

GridSpecFromSubplotSpec is another way to create a nested grid inside an existing subplot area. It allows us to define a child grid based on a parent SubplotSpec.

Example

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.gridspec import GridSpecFromSubplotSpec

fig = plt.figure(figsize=(10, 7))

gs = GridSpec(1, 2, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax1.set_title("Main Chart")

nested_gs = GridSpecFromSubplotSpec(
    2,
    2,
    subplot_spec=gs[0, 1]
)

ax2 = fig.add_subplot(nested_gs[0, 0])
ax3 = fig.add_subplot(nested_gs[0, 1])
ax4 = fig.add_subplot(nested_gs[1, :])

ax2.set_title("Chart 2")
ax3.set_title("Chart 3")
ax4.set_title("Wide Chart")

plt.tight_layout()
plt.show()

Expected Output

Left section:
One main chart.

Right section:
A nested 2 × 2 grid.

Top row:
Two separate charts.

Bottom row:
One chart spanning both columns.
Important: A nested GridSpec is useful when a complex figure needs independent layout control inside different sections of the parent figure.

10. Controlling GridSpec Spacing

GridSpec supports spacing and margin parameters. These parameters help control the space between rows, columns and the boundaries of the figure.

Parameter Description
wspace Controls horizontal spacing between grid columns.
hspace Controls vertical spacing between grid rows.
left Controls the left boundary of the grid.
right Controls the right boundary of the grid.
top Controls the top boundary of the grid.
bottom Controls the bottom boundary of the grid.

Example

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(10, 6))

gs = GridSpec(
    2,
    2,
    figure=fig,
    left=0.10,
    right=0.95,
    bottom=0.10,
    top=0.90,
    wspace=0.4,
    hspace=0.5
)

for row in range(2):
    for col in range(2):
        ax = fig.add_subplot(gs[row, col])
        ax.set_title(f"Row {row}, Column {col}")

plt.show()

Expected Output

A 2 × 2 GridSpec layout.

The figure uses customized margins.
Horizontal and vertical spacing are controlled
using wspace and hspace.

11. Difference Between Advanced Grid Methods

Matplotlib provides several tools for creating advanced subplot arrangements. Each tool has a different purpose.

Method Main Purpose Useful For
GridSpec Defines a flexible grid of rows and columns. Unequal sizes and subplot spanning.
subplot_mosaic() Creates layouts using labels and visual patterns. Readable dashboard layouts.
subgridspec() Creates a nested grid inside a parent grid region. Complex multi-section figures.
GridSpecFromSubplotSpec Creates a child GridSpec from a parent SubplotSpec. Advanced nested layouts.
add_subplot() Creates an Axes object in a selected grid position. Placing charts in GridSpec cells.

12. Practical Example: Business Analytics Dashboard

Let's create a business analytics dashboard with one large sales chart and three smaller charts. We will use GridSpec to control the layout and subplot sizes.

Complete Python Program

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

months = ["Jan", "Feb", "Mar", "Apr", "May"]

sales = [100, 150, 130, 180, 200]
profit = [30, 45, 40, 60, 75]
customers = [50, 65, 60, 80, 95]
orders = [40, 55, 50, 70, 85]

fig = plt.figure(figsize=(12, 8))

gs = GridSpec(
    2,
    2,
    figure=fig,
    width_ratios=[2, 1],
    height_ratios=[1, 1]
)

# Large sales chart
ax1 = fig.add_subplot(gs[:, 0])
ax1.plot(
    months,
    sales,
    marker="o",
    color="blue"
)
ax1.set_title("Monthly Sales")
ax1.set_ylabel("Sales Amount")

# Profit chart
ax2 = fig.add_subplot(gs[0, 1])
ax2.bar(
    months,
    profit,
    color="green"
)
ax2.set_title("Monthly Profit")

# Customer chart
ax3 = fig.add_subplot(gs[1, 1])
ax3.plot(
    months,
    customers,
    marker="s",
    color="orange"
)
ax3.set_title("Customer Growth")

fig.suptitle("Business Analytics Dashboard")

plt.tight_layout()
plt.show()

Expected Output

Business Analytics Dashboard

Left side:
Monthly Sales - Large line chart spanning two rows.

Right top:
Monthly Profit - Bar chart.

Right bottom:
Customer Growth - Line chart.

The dashboard uses different subplot sizes
with GridSpec width ratios and row spanning.
Real-world use: Advanced grids are useful for business dashboards, scientific reports, financial analysis, monitoring systems and applications that display charts with different levels of importance.

13. Common Mistakes in Advanced Grids

1. Incorrect Grid Indexing

GridSpec uses zero-based row and column indexes. Always check the number of rows and columns before selecting a grid position.

2. Overlapping Grid Positions

Avoid assigning multiple Axes objects to the same GridSpec region unintentionally. Check all selected ranges when creating spanning subplots.

3. Incorrect Ratio Values

The number of values in width_ratios should match the number of grid columns. The number of values in height_ratios should match the number of grid rows.

4. Repeating Labels Incorrectly in subplot_mosaic()

Repeated labels are used to make a subplot span multiple grid positions. Make sure each repeated label represents one connected region in the mosaic.

5. Making Nested Layouts Too Complex

Too many nested grids can make code difficult to maintain. Divide complex figures into logical sections and use meaningful variable names.

Important: GridSpec and subplot_mosaic() provide flexible layouts, but the final figure still needs suitable figure dimensions and spacing for readable chart labels.

14. Practice Questions

  1. What is GridSpec in Matplotlib?
  2. How do you create a GridSpec with three rows and two columns?
  3. What is the purpose of fig.add_subplot()?
  4. How can a subplot span multiple rows using GridSpec?
  5. What is the purpose of width_ratios?
  6. What is the difference between width_ratios and height_ratios?
  7. What is subplot_mosaic()?
  8. How do repeated labels work in subplot_mosaic()?
  9. What is a nested GridSpec?
  10. What is the purpose of subgridspec()?
  11. When should you use advanced grids instead of basic subplots?

Summary

Advanced grids in Matplotlib provide flexible ways to arrange multiple subplots inside a figure. They are useful when charts require different sizes, positions or layout structures.

The GridSpec class defines a grid of rows and columns. We can use fig.add_subplot() to create Axes objects in selected grid positions and use slicing to make subplots span multiple rows or columns.

The width_ratios and height_ratios parameters control the relative sizes of grid columns and rows. These options help us create layouts with large and small plotting areas.

The subplot_mosaic() function creates subplot layouts using labels. It makes complex arrangements easier to understand and provides convenient access to Axes objects through their labels.

Nested grids created with subgridspec() or GridSpecFromSubplotSpec allow us to divide a selected region into smaller subplot arrangements.

Understanding advanced grids helps us build professional dashboards, scientific visualizations and complex reports with complete control over subplot positions and sizes.