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

Layout Tuning in Matplotlib

Learn how to control spacing, margins and positioning between multiple subplots. Understand tight_layout(), subplots_adjust() and constrained layout for creating clean and readable figures.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand subplot layout management.
  • Identify spacing and overlapping problems.
  • Use plt.tight_layout() to adjust subplot spacing.
  • Customize margins using subplots_adjust().
  • Control horizontal and vertical spacing.
  • Understand constrained layout.
  • Use padding parameters to improve figure appearance.
  • Select a suitable layout method for different figures.

2. Introduction to Layout Tuning

When we create multiple subplots in Matplotlib, each plotting area requires enough space for its title, axis labels, tick labels and chart content.

Sometimes these elements overlap or appear too close to each other. Layout tuning helps us adjust the spacing and positioning of subplots so that the complete figure looks clean and readable.

Why Is Layout Tuning Important?

A properly arranged figure improves readability. It also helps viewers compare multiple charts without confusion. Layout management is especially important when creating dashboards, reports and scientific visualizations.

Poor Layout Improved Layout Long title overlaps Long title overlaps Axis labels Axis labels Plot 1 Plot 2 Plot 3 Plot 4

Layout tuning provides suitable spacing between subplot areas and their labels.

3. Using tight_layout()

The tight_layout() function automatically adjusts subplot parameters to reduce overlapping between titles, axis labels and tick labels.

It is useful when multiple charts are arranged in one figure and there is not enough space between them.

Syntax

plt.tight_layout()

Example Without tight_layout()

import matplotlib.pyplot as plt

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

ax[0, 0].set_title("Student Performance Analysis")
ax[0, 1].set_title("Monthly Sales Analysis")
ax[1, 0].set_title("Customer Growth Analysis")
ax[1, 1].set_title("Product Performance Analysis")

for axis in ax.flat:
    axis.set_xlabel("Category")
    axis.set_ylabel("Values")

plt.show()

Expected Output

A figure with four subplot areas.

Long titles and axis labels may have insufficient spacing.
Some subplot elements may appear crowded.

Example With tight_layout()

import matplotlib.pyplot as plt

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

ax[0, 0].set_title("Student Performance Analysis")
ax[0, 1].set_title("Monthly Sales Analysis")
ax[1, 0].set_title("Customer Growth Analysis")
ax[1, 1].set_title("Product Performance Analysis")

for axis in ax.flat:
    axis.set_xlabel("Category")
    axis.set_ylabel("Values")

plt.tight_layout()
plt.show()

Expected Output

A figure with four subplot areas.

Matplotlib adjusts the spacing to reduce overlapping.
Titles and axis labels receive more suitable space.
Tip: Use plt.tight_layout() as a convenient first option when subplot titles and labels are too close to one another.

4. tight_layout() Parameters

The tight_layout() function provides parameters that allow us to control padding around subplot elements.

Parameter Description
pad Controls padding between the figure edge and subplot content.
h_pad Controls vertical padding between subplot rows.
w_pad Controls horizontal padding between subplot columns.
rect Defines the rectangle area in which subplots are arranged.

Example Using pad

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize=(9, 6))

for i, axis in enumerate(ax.flat):
    axis.set_title(f"Chart {i + 1}")
    axis.set_xlabel("X Values")
    axis.set_ylabel("Y Values")

plt.tight_layout(pad=3.0)
plt.show()

Expected Output

Four subplots with additional padding
between the figure boundary and subplot content.

Example Using h_pad and w_pad

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize=(9, 6))

for i, axis in enumerate(ax.flat):
    axis.set_title(f"Chart {i + 1}")
    axis.set_xlabel("Category")
    axis.set_ylabel("Values")

plt.tight_layout(
    pad=2.0,
    h_pad=2.5,
    w_pad=2.5
)

plt.show()

Expected Output

Four subplots with customized horizontal
and vertical padding between subplot areas.

5. Using subplots_adjust()

The subplots_adjust() function gives us manual control over the margins and spacing of subplot areas.

Unlike automatic layout adjustment, this function allows us to specify exact values for the left, right, top and bottom boundaries, along with horizontal and vertical spacing.

Syntax

plt.subplots_adjust(
    left=None,
    bottom=None,
    right=None,
    top=None,
    wspace=None,
    hspace=None
)
Parameter Description
left Position of the left edge of the subplot area.
right Position of the right edge of the subplot area.
top Position of the top edge of the subplot area.
bottom Position of the bottom edge of the subplot area.
wspace Horizontal space between subplot columns, relative to average Axes width.
hspace Vertical space between subplot rows, relative to average Axes height.

Example

import matplotlib.pyplot as plt

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

for i, axis in enumerate(ax.flat):
    axis.plot([1, 2, 3], [10, 20, 30])
    axis.set_title(f"Chart {i + 1}")

plt.subplots_adjust(
    left=0.12,
    right=0.90,
    bottom=0.12,
    top=0.88
)

plt.show()

Expected Output

Four subplots with manually adjusted figure margins.

Left margin   : 0.12
Right margin  : 0.90
Bottom margin : 0.12
Top margin    : 0.88

6. Controlling Horizontal Spacing with wspace

The wspace parameter controls the horizontal space between columns of subplots.

Increasing its value creates more space between subplot columns. Reducing its value brings the columns closer together.

Small wspace Large wspace Plot 1 Plot 2 Plot 1 Plot 2

A larger wspace value creates more horizontal distance between subplot columns.

Example

import matplotlib.pyplot as plt

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

ax[0].plot([1, 2, 3], [10, 20, 30])
ax[0].set_title("First Plot")

ax[1].plot([1, 2, 3], [30, 20, 10])
ax[1].set_title("Second Plot")

plt.subplots_adjust(wspace=0.6)

plt.show()

Expected Output

Two horizontally arranged subplots.

The horizontal distance between the two subplot columns
is increased using wspace=0.6.

7. Controlling Vertical Spacing with hspace

The hspace parameter controls the vertical space between rows of subplots.

A larger value creates more vertical distance between rows, while a smaller value brings the rows closer together.

Small hspace Large hspace Plot 1 Plot 2 Plot 1 Plot 2

A larger hspace value creates more vertical distance between subplot rows.

Example

import matplotlib.pyplot as plt

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

ax[0].plot([1, 2, 3], [10, 20, 30])
ax[0].set_title("Top Plot")

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

plt.subplots_adjust(hspace=0.8)

plt.show()

Expected Output

Two vertically arranged subplots.

The vertical distance between the subplot rows
is increased using hspace=0.8.

8. Using Constrained Layout

Constrained layout is an automatic layout engine in Matplotlib. It adjusts the positions of subplots to accommodate titles, labels, tick labels, legends and colorbars.

We can enable it when creating a figure by using layout="constrained".

Example

import matplotlib.pyplot as plt

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

ax[0, 0].plot([1, 2, 3], [10, 20, 30])
ax[0, 0].set_title("Student Performance")

ax[0, 1].bar([1, 2, 3], [20, 30, 40])
ax[0, 1].set_title("Monthly Sales")

ax[1, 0].scatter([1, 2, 3], [30, 20, 40])
ax[1, 0].set_title("Customer Growth")

ax[1, 1].plot([1, 2, 3], [40, 30, 20])
ax[1, 1].set_title("Product Analysis")

plt.show()

Expected Output

A figure containing four different charts.

The constrained layout engine automatically manages
spacing between subplot elements.
Tip: Constrained layout is useful for complex figures containing multiple axes, long labels, legends or colorbars.

9. Adjusting Layout for a Figure Title

When we add a common title using fig.suptitle(), we may need additional space at the top of the figure.

The top parameter of subplots_adjust() can be used to adjust the upper boundary of the subplot area.

Example

import matplotlib.pyplot as plt

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

fig.suptitle(
    "Company Performance Dashboard",
    fontsize=16
)

for i, axis in enumerate(ax.flat):
    axis.plot([1, 2, 3], [10, 20, 30])
    axis.set_title(f"Department {i + 1}")

plt.subplots_adjust(top=0.85)

plt.show()

Expected Output

Common figure title:
Company Performance Dashboard

Four subplot charts appear below the common title.
Additional top margin is reserved for the figure title.

10. Using the rect Parameter

The rect parameter in tight_layout() defines the rectangle area in which subplot elements should fit.

It accepts four values representing the left, bottom, right and top boundaries in normalized figure coordinates.

Syntax

plt.tight_layout(
    rect=[left, bottom, right, top]
)

Example

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2, figsize=(9, 6))

fig.suptitle("Department Report")

for i, axis in enumerate(ax.flat):
    axis.plot([1, 2, 3], [10, 20, 30])
    axis.set_title(f"Department {i + 1}")

plt.tight_layout(
    rect=[0, 0, 1, 0.93]
)

plt.show()

Expected Output

A 2 × 2 subplot figure with a common title.

The subplot layout is adjusted within the specified
rectangle area, leaving space above for the figure title.

11. Difference Between Layout Methods

Matplotlib provides different ways to control subplot layout. Each method is useful for a different requirement.

Method Purpose Control
tight_layout() Automatically adjusts spacing around subplot elements. Automatic padding adjustment.
subplots_adjust() Manually adjusts subplot margins and spacing. Manual margin and spacing values.
layout="constrained" Uses an automatic layout engine to arrange subplot elements. Automatic layout management.

Which Method Should You Choose?

Use tight_layout() for quick spacing adjustments. Use subplots_adjust() when you need precise manual control over margins and spacing. Use constrained layout for more complex figures where automatic positioning is helpful.

12. Practical Example: Employee Performance Dashboard

Let's create an employee performance dashboard with four charts. We will use layout tuning to arrange the charts and reserve enough space for the main title.

Complete Python Program

import matplotlib.pyplot as plt

employees = ["Amit", "Rahul", "Priya", "Sneha"]

performance = [85, 75, 90, 80]
attendance = [95, 85, 98, 90]
projects = [5, 3, 6, 4]
hours = [40, 35, 45, 38]

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

# Performance chart
ax[0, 0].bar(employees, performance, color="skyblue")
ax[0, 0].set_title("Employee Performance")
ax[0, 0].set_ylabel("Performance Score")

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

# Project chart
ax[1, 0].scatter(
    employees,
    projects,
    color="red"
)
ax[1, 0].set_title("Completed Projects")
ax[1, 0].set_ylabel("Project Count")

# Working hours chart
ax[1, 1].bar(
    employees,
    hours,
    color="orange"
)
ax[1, 1].set_title("Working Hours")
ax[1, 1].set_ylabel("Hours")

fig.suptitle(
    "Employee Performance Dashboard",
    fontsize=16
)

plt.subplots_adjust(
    left=0.10,
    right=0.95,
    bottom=0.10,
    top=0.88,
    wspace=0.35,
    hspace=0.45
)

plt.show()

Expected Output

Employee Performance Dashboard

Top-left:
Employee Performance - Bar Chart

Top-right:
Employee Attendance - Line Chart

Bottom-left:
Completed Projects - Scatter Plot

Bottom-right:
Working Hours - Bar Chart

The figure uses customized margins and subplot spacing.
Real-world use: Layout tuning is important when preparing professional reports, dashboards, scientific charts and presentations where multiple visualizations must fit into one figure.

13. Common Mistakes in Layout Tuning

1. Using Too Little Spacing

Very small values for wspace and hspace may cause subplot titles and labels to overlap. Increase spacing when elements become difficult to read.

2. Using Too Much Spacing

Excessive spacing can make the actual plotting areas too small. Choose values that provide enough room without wasting figure space.

3. Overlapping Layout Methods

Avoid unnecessarily mixing automatic layout management with manual spacing adjustments. Choose one main layout strategy and verify the resulting figure.

4. Forgetting the Figure Title

When using fig.suptitle(), reserve sufficient top space so the title does not overlap with the first row of subplots.

Important: Do not call plt.tight_layout() after enabling constrained layout unless you intentionally want to change the layout strategy. Avoid combining competing layout adjustments.

14. Practice Questions

  1. What is layout tuning in Matplotlib?
  2. Why do we use plt.tight_layout()?
  3. What is the purpose of subplots_adjust()?
  4. What is the difference between wspace and hspace?
  5. Which parameters control the figure margins?
  6. What is constrained layout?
  7. How can you reserve space for a common figure title?
  8. What is the purpose of the pad parameter?
  9. How does the rect parameter work in tight_layout()?
  10. When should you use manual layout adjustments?

Summary

Layout tuning helps us organize multiple subplots inside a Matplotlib figure. It provides better spacing between charts, titles, axis labels and other visual elements, making the complete figure easier to understand.

The tight_layout() function automatically adjusts subplot spacing. Its padding parameters allow us to control the space around and between subplot elements.

The subplots_adjust() function provides manual control over figure margins and subplot spacing. Parameters such as left, right, top, bottom, wspace and hspace help position the subplot areas.

Constrained layout automatically manages the arrangement of subplot elements. It is useful for complex figures containing multiple charts, titles, labels, legends and colorbars.

Selecting the correct layout method helps create professional, readable and well-organized visualizations for dashboards, reports and data analysis projects.