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

Passing Axes in Matplotlib and Seaborn

Learn how to pass Matplotlib Axes objects to Seaborn and Pandas plotting functions to create organized, reusable and combined visualizations.

1. Learning Objectives

After completing this lesson, you will understand how to:

  • Understand the Matplotlib Axes object.
  • Create Figure and Axes objects using plt.subplots().
  • Pass an Axes object to Seaborn functions using ax.
  • Use Pandas plotting methods with an existing Axes object.
  • Combine multiple plotting libraries in the same visualization.
  • Create multiple plots using a single Figure.

2. What Does Passing Axes Mean?

In Matplotlib, an Axes object represents an individual plotting area. It contains the x-axis, y-axis, title, labels, grid and plotted data.

Passing Axes means providing an existing Matplotlib Axes object to another plotting function. That function then draws its visualization inside the specified plotting area.

Basic Syntax

fig, ax = plt.subplots()

sns.scatterplot(
    data=df,
    x="Experience",
    y="Salary",
    ax=ax
)

Here, ax=ax tells Seaborn to draw the scatter plot inside the Axes object created by Matplotlib.

Matplotlib Figure Axes Object (ax) X-axis Y-axis Seaborn and Pandas plots can draw inside this Axes

A Figure can contain one or more Axes objects. Each Axes is an individual plotting area.

3. Create an Axes Object Using Matplotlib

The plt.subplots() function creates a Figure and one or more Axes objects. It is commonly used when working with Seaborn and Pandas.

Example: Create a Single Axes

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [120, 150, 180, 160, 210]
}

df = pd.DataFrame(data)

fig, ax = plt.subplots(figsize=(8, 5))

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    ax=ax
)

ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

plt.tight_layout()
plt.show()

Output

Figure: Monthly Sales

A line chart is displayed in one Axes.
X-axis: Month
Y-axis: Sales
Data points: Jan=120, Feb=150, Mar=180, Apr=160, May=210

4. Passing Axes to Seaborn Functions

Seaborn plotting functions support the ax parameter. You can use it to decide exactly where a plot should appear.

4.1 Scatter Plot

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({
    "Experience": [1, 2, 3, 4, 5],
    "Salary": [20000, 25000, 32000, 40000, 50000]
})

fig, ax = plt.subplots(figsize=(8, 5))

sns.scatterplot(
    data=df,
    x="Experience",
    y="Salary",
    color="blue",
    s=100,
    ax=ax
)

ax.set_title("Experience vs Salary")

plt.tight_layout()
plt.show()

Output

Figure: Experience vs Salary

A scatter plot is displayed.
X-axis: Experience
Y-axis: Salary
Five data points represent the relationship between experience and salary.

4.2 Histogram

fig, ax = plt.subplots(figsize=(8, 5))

sns.histplot(
    data=df,
    x="Salary",
    bins=5,
    color="green",
    ax=ax
)

ax.set_title("Salary Distribution")

plt.tight_layout()
plt.show()

Output

Figure: Salary Distribution

A histogram is displayed inside the specified Axes.
The salary values are grouped into five bins.

4.3 Box Plot

fig, ax = plt.subplots(figsize=(8, 5))

sns.boxplot(
    data=df,
    y="Salary",
    color="orange",
    ax=ax
)

ax.set_title("Salary Distribution - Box Plot")

plt.tight_layout()
plt.show()

Output

Figure: Salary Distribution - Box Plot

A vertical box plot is displayed.
It shows the median, quartiles, whiskers and potential outliers.

5. Passing Axes to Pandas Plotting

Pandas plotting methods also support an ax parameter. This allows you to display a DataFrame plot inside an existing Matplotlib Axes.

Example: Pandas Line Plot

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "Month": ["Jan", "Feb", "Mar", "Apr"],
    "Sales": [100, 150, 130, 200]
})

fig, ax = plt.subplots(figsize=(8, 5))

df.plot(
    x="Month",
    y="Sales",
    kind="line",
    marker="o",
    ax=ax
)

ax.set_title("Monthly Sales Using Pandas")

plt.tight_layout()
plt.show()

Output

Figure: Monthly Sales Using Pandas

A line chart is displayed inside the existing Axes.
X-axis: Month
Y-axis: Sales
The chart is created using the Pandas DataFrame plot method.
Tip: Passing ax=ax helps you combine Pandas, Seaborn and Matplotlib without creating separate figures for every plotting function.

6. Combine Pandas and Seaborn on the Same Axes

You can draw multiple visual elements on the same Axes. For example, you can create a Pandas line plot and add Seaborn scatter points.

Example: Line and Scatter Combination

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({
    "Month": [1, 2, 3, 4, 5],
    "Sales": [100, 140, 130, 180, 220]
})

fig, ax = plt.subplots(figsize=(8, 5))

df.plot(
    x="Month",
    y="Sales",
    kind="line",
    marker="o",
    color="blue",
    ax=ax
)

sns.scatterplot(
    data=df,
    x="Month",
    y="Sales",
    color="red",
    s=100,
    ax=ax,
    label="Sales points"
)

ax.set_title("Monthly Sales: Line and Scatter")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.legend()

plt.tight_layout()
plt.show()

Output

Figure: Monthly Sales: Line and Scatter

A blue line connects the monthly sales values.
Red scatter points highlight the individual observations.
Both visual elements appear on the same Axes.

7. Passing Axes to Multiple Subplots

When you create multiple subplots, Matplotlib returns an array of Axes objects. You can pass each Axes object to a different Seaborn or Pandas plotting function.

Example: Two Subplots

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({
    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
    "Sales": [100, 150, 130, 180, 220],
    "Profit": [20, 35, 30, 45, 60]
})

fig, axes = plt.subplots(
    nrows=1,
    ncols=2,
    figsize=(12, 5)
)

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    marker="o",
    ax=axes[0]
)

sns.barplot(
    data=df,
    x="Month",
    y="Profit",
    ax=axes[1]
)

axes[0].set_title("Monthly Sales")
axes[1].set_title("Monthly Profit")

plt.tight_layout()
plt.show()

Output

Figure: Two Subplots

Left Axes:
Line chart showing monthly sales.

Right Axes:
Bar chart showing monthly profit.

Both charts are arranged horizontally in one Figure.

Example: Four Subplots

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

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    ax=axes[0, 0]
)

sns.barplot(
    data=df,
    x="Month",
    y="Profit",
    ax=axes[0, 1]
)

sns.scatterplot(
    data=df,
    x="Sales",
    y="Profit",
    ax=axes[1, 0]
)

sns.histplot(
    data=df,
    x="Sales",
    ax=axes[1, 1]
)

axes[0, 0].set_title("Sales Trend")
axes[0, 1].set_title("Profit by Month")
axes[1, 0].set_title("Sales vs Profit")
axes[1, 1].set_title("Sales Distribution")

plt.tight_layout()
plt.show()

Output

Figure: Four Subplots

Top-left: Sales line chart.
Top-right: Monthly profit bar chart.
Bottom-left: Sales vs profit scatter plot.
Bottom-right: Sales distribution histogram.

All four plots are displayed in one Figure.

8. Understanding Axes Indexing

The structure of the returned Axes object depends on the number of rows and columns passed to plt.subplots().

Code Axes Result Access Example
plt.subplots() Single Axes object ax
plt.subplots(1, 2) One-dimensional array axes[0]
plt.subplots(2, 1) One-dimensional array axes[1]
plt.subplots(2, 2) Two-dimensional array axes[0, 1]

Using Squeeze=False

You can use squeeze=False to ensure that the returned Axes collection is always a two-dimensional array, even when you create a single subplot.

fig, axes = plt.subplots(
    1,
    2,
    figsize=(10, 4),
    squeeze=False
)

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    ax=axes[0, 0]
)

sns.barplot(
    data=df,
    x="Month",
    y="Profit",
    ax=axes[0, 1]
)

plt.tight_layout()
plt.show()

Output

Figure: Two Subplots

axes is a two-dimensional array.
First plot uses axes[0, 0].
Second plot uses axes[0, 1].

9. Customize an Existing Axes

After passing an Axes object to a plotting function, you can use Matplotlib methods to customize the same plotting area.

fig, ax = plt.subplots(figsize=(8, 5))

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    marker="o",
    ax=ax
)

ax.set_title(
    "Monthly Sales Report",
    fontsize=16,
    fontweight="bold"
)

ax.set_xlabel("Month", fontsize=12)
ax.set_ylabel("Sales Amount", fontsize=12)

ax.grid(
    True,
    linestyle="--",
    alpha=0.5
)

ax.set_ylim(0, 250)

plt.tight_layout()
plt.show()

Output

Figure: Monthly Sales Report

Title: Monthly Sales Report
X-axis: Month
Y-axis: Sales Amount
Grid: Dashed grid lines
Y-axis range: 0 to 250

The Seaborn chart is customized using Matplotlib Axes methods.

10. Common Mistakes

Mistake Explanation Correct Approach
Forgetting ax=ax The plot may be created on a different or automatically selected Axes. Pass the intended Axes object.
Incorrect indexing Using axes[0, 0] for a one-dimensional array causes an error. Check the subplot dimensions.
Using ax instead of axes Multiple subplots return an Axes collection. Use the correct variable and index.
Creating separate Figures unnecessarily Plots may appear in separate windows or outputs. Reuse the same Axes object when combining plots.
Missing labels and titles The chart becomes difficult to understand. Use Axes methods such as set_title() and set_xlabel().
Important: Do not pass an Axes collection where a single Axes object is expected. For example, in a 2 × 2 subplot layout, use axes[0, 0] rather than the entire axes collection.

11. Best Practices

  • Create Figures and Axes explicitly using plt.subplots().
  • Pass the correct Axes object to every Seaborn or Pandas plotting function.
  • Use meaningful variable names such as fig, ax and axes.
  • Use multiple Axes objects to organize related charts.
  • Customize labels, titles, limits and grids using Matplotlib methods.
  • Use plt.tight_layout() to reduce overlapping elements.
  • Use plt.show() to display the completed Figure in a script.

12. Practical Activity

Employee Performance Dashboard

Create a dashboard using Matplotlib, Pandas and Seaborn.

Requirements:

  1. Create a DataFrame containing Employee, Experience, Salary and Performance.
  2. Create a Figure with two rows and two columns.
  3. Use a Seaborn scatter plot for Experience vs Salary.
  4. Use a Seaborn bar chart for Employee Performance.
  5. Use a Pandas line plot for Salary trends.
  6. Use a Seaborn histogram for Salary distribution.
  7. Pass the correct Axes object to every plotting function.
  8. Add titles, axis labels and grid lines.

13. Practice Questions

  1. What is an Axes object in Matplotlib?
  2. What is the purpose of the ax parameter in Seaborn?
  3. How do you create a Figure with a single Axes?
  4. How can you pass an Axes object to a Pandas plotting method?
  5. How do you access the second Axes in a one-row, two-column layout?
  6. What is the purpose of squeeze=False?
  7. How can you combine a Pandas plot and a Seaborn plot on the same Axes?
  8. What is the difference between ax and axes?

Summary

Passing Axes is an important technique for combining Matplotlib, Seaborn and Pandas visualizations. An Axes object represents an individual plotting area inside a Figure.

The plt.subplots() function creates Figure and Axes objects. Seaborn and Pandas plotting functions can receive an existing Axes object through the ax parameter.

This approach makes it possible to combine multiple plots in one Figure, organize dashboards, and customize visualizations using Matplotlib methods.