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.
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.
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.
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.
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()
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.
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()
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.
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() |
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:
- Import Matplotlib using pyplot.
- Create a Figure with figsize=(10, 5).
- Create one Axes object.
- Plot the student marks using ax.plot().
- Add a chart title and axis labels.
- Set a suitable Figure background color.
- Add grid lines and a legend.
- Display the final visualization.
Practice Questions
- What is a Figure canvas in Matplotlib?
- Which function is used to create a Figure?
- What is the purpose of figsize?
- What does the dpi parameter control?
- How can you add Axes to an existing Figure?
- What does add_subplot(111) represent?
- What is the difference between plt.figure() and plt.subplots()?
- How can you change the Figure background color?
- 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.