Pyplot vs Object-Oriented API
Learn the two main approaches used to create and customize visualizations in Matplotlib.
Understand pyplot functions, Figure and Axes objects, compare both approaches and learn when to use each method.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand the pyplot interface in Matplotlib.
- Understand the Object-Oriented API.
- Explain the difference between Figure and Axes objects.
- Create charts using pyplot functions.
- Create charts using the Object-Oriented approach.
- Understand the role of
figandax. - Compare both plotting approaches.
- Choose the appropriate approach for different projects.
2. Introduction to Matplotlib APIs
Matplotlib provides different ways to create and customize charts. Two commonly used approaches are the pyplot interface and the Object-Oriented API.
The pyplot interface provides simple functions such as
plt.plot(), plt.title() and
plt.show() to create visualizations.
The Object-Oriented API works directly with Figure and Axes objects. It provides more explicit control over individual charts and their components.
Two Approaches
Pyplot Approach:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.title('My First Chart')
plt.show()
Object-Oriented Approach:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
ax.set_title('My First Chart')
plt.show()
Both examples create a line chart, but they use different interfaces to control the plotting process.
3. Understanding the Pyplot Interface
Pyplot is a module inside Matplotlib that provides a collection of functions for creating and managing charts.
It is commonly imported using the alias plt.
Many pyplot functions operate on the current Figure and
current Axes.
Basic Pyplot Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y)
plt.title('Pyplot Line Chart')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.grid(True)
plt.show()
Output
Line chart displayed with:
- Five data points.
- Title: Pyplot Line Chart.
- X-axis label: X Values.
- Y-axis label: Y Values.
- Grid lines enabled.
In this example, pyplot automatically uses the current plotting context. We do not explicitly create or store Figure and Axes objects.
4. Common Pyplot Functions
Pyplot provides many functions for creating and customizing charts.
| Function | Purpose |
|---|---|
| plt.plot() | Creates a line chart. |
| plt.scatter() | Creates a scatter plot. |
| plt.bar() | Creates a bar chart. |
| plt.hist() | Creates a histogram. |
| plt.title() | Sets the title of the current Axes. |
| plt.xlabel() | Sets the X-axis label. |
| plt.ylabel() | Sets the Y-axis label. |
| plt.legend() | Displays the legend of the current Axes. |
| plt.grid() | Controls grid visibility. |
| plt.figure() | Creates a new Figure. |
| plt.subplots() | Creates a Figure and one or more Axes. |
| plt.show() | Displays the created figures. |
5. Understanding the Object-Oriented API
The Object-Oriented API allows us to work directly with Matplotlib objects such as Figure and Axes.
Instead of relying on the current plotting context, we store references to the objects and call their methods directly.
The most common way to create these objects is by using
plt.subplots().
Basic Syntax
fig, ax = plt.subplots()
Here, fig represents the Figure object and
ax represents the Axes object.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Object-Oriented Line Chart')
ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.grid(True)
plt.show()
Output
Line chart displayed with:
- Five data points.
- Title: Object-Oriented Line Chart.
- X-axis label: X Values.
- Y-axis label: Y Values.
- Grid lines enabled.
The chart looks similar to the pyplot example, but here all chart operations are performed through the Axes object.
6. Understanding Figure and Axes Objects
Figure and Axes are important components of Matplotlib's Object-Oriented API.
Figure Object
A Figure is the overall container that holds one or more Axes, titles, legends, colour bars and other chart elements.
Axes Object
An Axes object represents an individual plotting area. It contains the X-axis, Y-axis, plotted data, labels, title, grid and other chart elements.
Conceptual diagram showing an Axes object inside a Figure object.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(type(fig))
print(type(ax))
Output
<class 'matplotlib.figure.Figure'>
<class 'matplotlib.axes._axes.Axes'>
The exact Axes class representation can vary across
Matplotlib versions. The important point is that
fig and ax are separate objects
with different responsibilities.
7. Working with Figure Methods
The Figure object provides methods to control the overall figure and its layout.
| Figure Method | Purpose |
|---|---|
| fig.suptitle() | Sets an overall title for the Figure. |
| fig.set_size_inches() | Changes the Figure dimensions. |
| fig.savefig() | Saves the Figure to a file. |
| fig.tight_layout() | Adjusts spacing to reduce overlapping elements. |
| fig.subplots_adjust() | Manually adjusts subplot spacing. |
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.set_size_inches(9, 5)
fig.suptitle('Company Sales Report')
ax.plot([1, 2, 3, 4], [100, 150, 130, 200])
ax.set_title('Monthly Sales')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')
fig.tight_layout()
plt.show()
Output
Figure displayed with:
- Overall Figure title: Company Sales Report.
- Axes title: Monthly Sales.
- Figure size: 9 x 5 inches.
- X-axis label: Month.
- Y-axis label: Sales.
8. Working with Axes Methods
The Axes object provides methods for plotting data and customizing individual chart elements.
| Axes Method | Purpose |
|---|---|
| ax.plot() | Creates a line chart. |
| ax.scatter() | Creates a scatter plot. |
| ax.bar() | Creates a bar chart. |
| ax.hist() | Creates a histogram. |
| ax.set_title() | Sets the Axes title. |
| ax.set_xlabel() | Sets the X-axis label. |
| ax.set_ylabel() | Sets the Y-axis label. |
| ax.legend() | Displays the Axes legend. |
| ax.grid() | Controls Axes grid lines. |
| ax.set_xlim() | Sets X-axis limits. |
| ax.set_ylim() | Sets Y-axis limits. |
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y, marker='o', label='Sales')
ax.set_title('Sales Performance')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')
ax.set_xlim(1, 5)
ax.set_ylim(0, 35)
ax.grid(True)
ax.legend()
plt.show()
Output
Sales Performance chart displayed with:
- X-axis limits from 1 to 5.
- Y-axis limits from 0 to 35.
- Sales line with circular markers.
- Grid lines and legend.
- Customized title and axis labels.
9. Pyplot vs Object-Oriented API Comparison
Both approaches can create the same types of charts, but they differ in how plotting operations are managed.
| Feature | Pyplot Interface | Object-Oriented API |
|---|---|---|
| Approach | Uses pyplot functions. | Uses Figure and Axes objects. |
| Plotting | plt.plot() | ax.plot() |
| Title | plt.title() | ax.set_title() |
| X-axis Label | plt.xlabel() | ax.set_xlabel() |
| Y-axis Label | plt.ylabel() | ax.set_ylabel() |
| Grid | plt.grid() | ax.grid() |
| Figure Creation | Often managed implicitly or with plt.figure(). | Explicitly managed through Figure objects. |
| Multiple Axes | Requires managing the current plotting context. | Each Axes can be accessed directly. |
| Code Organization | Simple for quick plotting. | Suitable for structured and complex plotting code. |
| Control | Uses the current plotting state. | Provides explicit object-level control. |
10. Creating the Same Chart Using Both Approaches
Let's create the same sales chart using pyplot and the Object-Oriented API.
Example 1: Pyplot Approach
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 150, 130, 180, 220]
plt.plot(months, sales, marker='o', label='Sales')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.grid(True)
plt.legend()
plt.show()
Output
Monthly Sales chart displayed using pyplot.
- Sales data plotted as a line.
- Circular markers displayed.
- Title and axis labels added.
- Grid and legend displayed.
Example 2: Object-Oriented Approach
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 150, 130, 180, 220]
fig, ax = plt.subplots()
ax.plot(months, sales, marker='o', label='Sales')
ax.set_title('Monthly Sales')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')
ax.grid(True)
ax.legend()
plt.show()
Output
Monthly Sales chart displayed using
the Object-Oriented API.
- Sales data plotted as a line.
- Circular markers displayed.
- Title and axis labels added.
- Grid and legend displayed.
Both programs create a similar chart. The main difference is how we access and control the plotting operations.
11. Managing Multiple Charts with Object-Oriented API
The Object-Oriented API is particularly useful when working with multiple charts in a single Figure.
We can create multiple Axes objects and control each one independently.
Example
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 150, 130, 180, 220]
profit = [20, 35, 30, 45, 60]
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
# First Axes
axes[0].plot(months, sales, marker='o')
axes[0].set_title('Monthly Sales')
axes[0].set_xlabel('Month')
axes[0].set_ylabel('Sales')
# Second Axes
axes[1].bar(months, profit)
axes[1].set_title('Monthly Profit')
axes[1].set_xlabel('Month')
axes[1].set_ylabel('Profit')
fig.tight_layout()
plt.show()
Output
One Figure containing two charts:
1. Monthly Sales:
- Line chart.
- Sales values for five months.
- Circular markers.
2. Monthly Profit:
- Bar chart.
- Profit values for five months.
Both charts have independent Axes objects.
12. Advantages of the Object-Oriented API
The Object-Oriented API provides explicit control over individual Figure and Axes objects.
- Better control over individual charts.
- Easy management of multiple subplots.
- Clear separation between Figure and Axes.
- Improved code organization for complex visualizations.
- Convenient reuse of Axes objects in functions.
- Less dependence on the current plotting context.
- Suitable for dashboards and reusable plotting components.
13. When Should You Use Each Approach?
Use Pyplot When:
- You want to create a quick and simple chart.
- You are learning basic Matplotlib plotting.
- You are working with a short plotting script.
- You need a simple visualization for data exploration.
Use Object-Oriented API When:
- You are creating multiple charts in one Figure.
- You need independent control over Axes objects.
- You are building dashboards or reports.
- You are writing reusable plotting functions.
- You are developing larger visualization applications.
14. Common Mistakes and Solutions
| Common Mistake | Reason | Solution |
|---|---|---|
| Using plt.title() with an Axes object | Mixing pyplot and Axes methods without considering the current Axes. | Use ax.set_title() when working directly with an Axes object. |
| Using the wrong variable | Confusing Figure and Axes objects. | Use fig for Figure operations and ax for Axes operations. |
| Incorrect subplot indexing | Accessing the wrong Axes object. | Check the structure returned by plt.subplots(). |
| Overlapping chart elements | Insufficient layout spacing. | Use fig.tight_layout() or adjust subplot spacing. |
| Unexpected current chart | Pyplot functions act on the current plotting context. | Use explicit Axes references for independent chart control. |
15. Best Practices
- Prefer the Object-Oriented API for complex plotting tasks.
- Use meaningful variable names such as fig and ax.
- Use Figure methods for overall figure configuration.
- Use Axes methods for individual chart customization.
- Use separate Axes references when creating multiple charts.
- Keep plotting code organized and reusable.
- Use pyplot functions for simple and quick plotting tasks.
- Avoid depending unnecessarily on the current Axes in complex programs.
16. Practical Activity: Create a Student Performance Dashboard
Create a Figure containing two charts to compare student performance using the Object-Oriented API.
Activity Requirements
- Create a Figure with two Axes objects.
- Display student marks using a line chart.
- Display student attendance using a bar chart.
- Add titles to both charts.
- Add X-axis and Y-axis labels.
- Enable grid lines on the marks chart.
- Adjust the overall Figure layout.
Python Code
import matplotlib.pyplot as plt
students = ['Amit', 'Rahul', 'Priya', 'Sneha', 'Neha']
marks = [75, 85, 90, 70, 95]
attendance = [80, 90, 95, 75, 98]
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
# Marks chart
axes[0].plot(students, marks, marker='o', color='blue')
axes[0].set_title('Student Marks')
axes[0].set_xlabel('Students')
axes[0].set_ylabel('Marks')
axes[0].grid(True)
# Attendance chart
axes[1].bar(students, attendance, color='green')
axes[1].set_title('Student Attendance')
axes[1].set_xlabel('Students')
axes[1].set_ylabel('Attendance (%)')
fig.suptitle('Student Performance Dashboard')
fig.tight_layout()
plt.show()
Output
Student Performance Dashboard displayed.
First chart:
- Student Marks line chart.
- Five student records.
- Marks displayed on the Y-axis.
Second chart:
- Student Attendance bar chart.
- Five student records.
- Attendance percentages displayed.
Both charts are displayed in one Figure.
17. Practice Questions
Basic Questions
- What is the pyplot interface in Matplotlib?
- What is the Object-Oriented API?
- What is the purpose of plt.subplots()?
- What is a Figure object?
- What is an Axes object?
- What is the difference between plt.plot() and ax.plot()?
- Which approach is useful for managing multiple subplots?
Practical Questions
- Create a line chart using pyplot.
- Create the same chart using the Object-Oriented API.
- Set a chart title using ax.set_title().
- Change the Figure size using fig.set_size_inches().
- Create two charts using plt.subplots().
- Display a line chart and a bar chart in one Figure.
- Use Figure and Axes methods to customize a chart.
Summary
Matplotlib provides two commonly used plotting approaches: the pyplot interface and the Object-Oriented API. The pyplot interface uses functions such as plt.plot(), plt.title() and plt.xlabel() to create and customize charts.
The Object-Oriented API works directly with Figure and Axes objects. The Figure represents the overall chart container, while the Axes represents an individual plotting area. The plt.subplots() function is commonly used to create these objects.
Figure methods control the overall figure, while Axes methods control individual chart elements. This separation provides better control when creating multiple charts and complex visualizations.
Pyplot is convenient for quick plotting and simple scripts. The Object-Oriented API is generally more suitable for structured applications, dashboards, multiple subplots and reusable visualization code.