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

Creating Canvas in Matplotlib

In this lesson, you will learn how to create a Figure canvas in Matplotlib, add Axes to the Figure, configure the plotting area, and build a basic visualization using the object-oriented approach.

1. Learning Objectives

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

  • Understand the concept of a Figure canvas in Matplotlib.
  • Create a Figure using the figure() function.
  • Understand how Figure and Axes work together.
  • Create Axes using add_subplot().
  • Create a Figure and Axes together using subplots().
  • Configure Figure size, resolution, and background color.
  • Create a basic chart using the object-oriented API.

2. What Is a Canvas in Matplotlib?

In Matplotlib, a Figure acts as the main canvas where visualizations are created. It is the top-level container that holds Axes, titles, labels, legends, and other graphical elements.

A Figure provides the drawing area for a visualization. We can create a Figure first and then add one or more Axes objects to display charts.

Example: Student Performance Report

Suppose Omkar wants to display student marks using a line chart. He can create a Figure as the canvas and add an Axes object inside it to plot student performance data.

The Figure manages the complete visualization, while the Axes object provides the coordinate system where the actual chart is drawn.

Figure Canvas Axes - Plotting Area Figure contains the plotting area and other visual elements
Figure 1: A Figure acts as the canvas and Axes provide the plotting area.

3. Creating a Figure Using plt.figure()

Matplotlib provides the figure() function to create a new Figure object. We can use this function when we want to create and configure the canvas before adding Axes.

Basic Syntax

import matplotlib.pyplot as plt

fig = plt.figure()

plt.show()

Explanation:

  • import matplotlib.pyplot as plt: Imports the pyplot module.
  • plt.figure(): Creates a new Figure object.
  • fig: Stores the reference to the Figure.
  • plt.show(): Displays the figure in a supported interactive environment.
Tip: Creating a Figure does not automatically create a plotting area. Add an Axes object before drawing a chart.

4. Understanding Figure Parameters

The figure() function provides parameters that allow us to control the size, resolution, and appearance of the canvas.

Parameter Purpose Example
figsize Defines Figure width and height in inches. figsize=(8, 5)
dpi Defines dots per inch. dpi=100
facecolor Sets the Figure background color. facecolor="lightblue"
num Provides a Figure number or label. num="Sales Report"
clear Clears an existing Figure when applicable. clear=True

Example: Configure Figure Properties

import matplotlib.pyplot as plt

fig = plt.figure(
    figsize=(8, 5),
    dpi=100,
    facecolor="lightyellow"
)

plt.show()

In this example, we create a Figure with a width of 8 inches, a height of 5 inches, a resolution of 100 DPI, and a light yellow background.

5. Understanding Figure Size

The figsize parameter controls the physical dimensions of a Figure. It accepts a tuple containing width and height in inches.

Syntax

fig = plt.figure(figsize=(width, height))

Example

import matplotlib.pyplot as plt

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

plt.show()

Here, the Figure width is 10 inches and the height is 5 inches. This creates a landscape-oriented canvas.

Landscape figsize=(10, 5) Portrait figsize=(5, 8) Wide canvas Tall canvas
Figure 2: Different Figure dimensions create different canvas shapes.
Tip: Use a wider Figure for wide data visualizations and a taller Figure when the content needs more vertical space.

6. Adding Axes to a Figure

After creating a Figure, we need an Axes object to draw a chart. The add_subplot() method creates an Axes and places it inside the specified Figure.

Basic Syntax

fig.add_subplot(rows, columns, index)

Example

import matplotlib.pyplot as plt

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

ax = fig.add_subplot(111)

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("My First Chart")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")

plt.show()

Explanation:

  • fig: Represents the Figure object.
  • add_subplot(111): Creates one Axes in a 1-row, 1-column grid.
  • ax.plot(): Draws the line chart.
  • ax.set_title(): Adds the chart title.
  • ax.set_xlabel(): Sets the X-axis label.
  • ax.set_ylabel(): Sets the Y-axis label.
Tip: The object-oriented approach uses Figure and Axes references directly. It is useful when creating complex visualizations.

7. Understanding add_subplot() Parameters

The add_subplot() method divides a Figure into a grid and creates an Axes at the requested position.

Argument Meaning Example
rows Number of rows in the grid. 2
columns Number of columns in the grid. 2
index Position of the Axes, starting from 1. 1

Example: Create Two Subplots

import matplotlib.pyplot as plt

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

ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

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

ax2.bar(["A", "B", "C"], [15, 25, 20])
ax2.set_title("Bar Chart")

plt.show()
One Figure Axes 1 - Line Chart Axes 2 - Bar Chart
Figure 3: A single Figure containing two separate Axes objects.

8. Creating Figure and Axes Using plt.subplots()

Matplotlib also provides the subplots() function. It creates a Figure and one or more Axes objects together. This is a convenient approach for most plotting applications.

Basic Syntax

fig, ax = plt.subplots()

Example

import matplotlib.pyplot as plt

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

ax.plot([1, 2, 3, 4], [5, 10, 15, 20])

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

plt.show()

Explanation:

  • fig: Stores the Figure object.
  • ax: Stores the Axes object.
  • plt.subplots(): Creates the Figure and its Axes together.
Tip: Use plt.subplots() when you want to create a Figure and Axes together. It provides a simple and clear way to work with Matplotlib's object-oriented API.

9. Customizing Figure Background

We can change the background color of a Figure using the facecolor parameter. This controls the appearance of the overall canvas.

Example

import matplotlib.pyplot as plt

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

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("Customized Figure")

plt.show()

In this example, the Figure background is set to light yellow. The Axes background can be customized separately.

Changing Axes Background

fig, ax = plt.subplots(facecolor="lightyellow")

ax.set_facecolor("white")

ax.plot([1, 2, 3], [10, 20, 30])

plt.show()
Warning: Figure background and Axes background are different. Changing the Figure facecolor does not automatically change the Axes facecolor.

10. Complete Example: Creating a Matplotlib Canvas

Let's create a complete Figure containing a line chart with a title, axis labels, grid lines, and legend.

Monthly Sales Report

import matplotlib.pyplot as plt

# Create Figure and Axes
fig, ax = plt.subplots(
    figsize=(9, 5),
    dpi=100,
    facecolor="white"
)

# Sample data
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [100, 150, 130, 180, 220]

# Create line chart
ax.plot(
    months,
    sales,
    color="blue",
    marker="o",
    linewidth=2,
    label="Monthly Sales"
)

# Add chart details
ax.set_title("Monthly Sales Report")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

# Add grid and legend
ax.grid(True, linestyle="--", alpha=0.5)
ax.legend()

# Adjust layout
fig.tight_layout()

# Display chart
plt.show()

This example demonstrates how a Figure and Axes work together to create a complete visualization.

Monthly Sales Report Jan Feb Mar Apr May Month Sales
Figure 4: Example preview of a monthly sales visualization.

11. Difference Between plt.figure() and plt.subplots()

Both functions are used to create Figures, but they provide different ways of working with Axes.

plt.figure() plt.subplots()
Creates a Figure object. Creates a Figure and Axes together.
Axes can be added later using add_subplot(). Axes are returned directly by the function.
Useful when you want to build the Figure step by step. Convenient for creating charts and subplot layouts.
fig = plt.figure() fig, ax = plt.subplots()
Tip: Both approaches are valid. Select the method that makes your plotting code easier to understand and maintain.

12. Common Mistakes While Creating a Canvas

Common Mistake Correct Approach
Creating a Figure but not adding Axes. Add Axes using add_subplot() or subplots().
Using an invalid subplot index. Keep the index within the available grid positions.
Confusing Figure size with pixels. Remember that figsize uses inches.
Changing Figure background but expecting Axes background to change. Use ax.set_facecolor() separately.
Using the wrong variable for Axes methods. Call plotting methods using the Axes reference.
Not displaying a chart in a normal Python script. Use plt.show() when required by the environment.

13. Classroom Practical Activity

Activity: Create a Student Performance Canvas

Create a Figure canvas to display the marks of five students. Use the following sample data:

students = ["Amit", "Rahul", "Priya", "Sneha", "Om"]
marks = [75, 82, 90, 68, 95]

Complete the following tasks:

  1. Import Matplotlib using pyplot.
  2. Create a Figure with figsize=(10, 5).
  3. Create one Axes object.
  4. Plot the student marks using ax.plot().
  5. Add a chart title and axis labels.
  6. Set a suitable Figure background color.
  7. Add grid lines and a legend.
  8. Display the final visualization.

Practice Questions

  1. What is a Figure canvas in Matplotlib?
  2. Which function is used to create a Figure?
  3. What is the purpose of figsize?
  4. What does the dpi parameter control?
  5. How can you add Axes to an existing Figure?
  6. What does add_subplot(111) represent?
  7. What is the difference between plt.figure() and plt.subplots()?
  8. How can you change the Figure background color?
  9. Can one Figure contain multiple Axes objects?

Summary

In this lesson, you learned how to create a canvas using Matplotlib. A Figure acts as the main container for a visualization, while Axes provide the plotting areas where charts are drawn.

You explored plt.figure(), add_subplot(), and plt.subplots(). You also learned how to configure Figure dimensions, resolution, background color, and create a complete line chart using the object-oriented API.

In the next lesson, we will learn about Figure dimensions and resolution and understand how they affect the appearance and quality of visualizations.