Transitioning Methods in Matplotlib
Learn how to convert existing pyplot plotting code into the Object-Oriented API using Figure and Axes methods.
Understand method mapping, code conversion, chart customization and practical techniques for writing reusable plotting programs.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand the meaning of transitioning between Matplotlib APIs.
- Convert pyplot functions into Axes methods.
- Identify methods that belong to Figure and Axes objects.
- Convert line, bar, scatter and histogram examples.
- Understand the use of Figure-level methods.
- Manage multiple charts using Axes references.
- Refactor existing plotting code into reusable functions.
- Apply best practices when transitioning to the Object-Oriented API.
2. Introduction to Transitioning Methods
In Matplotlib, transitioning methods means changing an existing plotting program from the pyplot interface to the Object-Oriented API.
In the pyplot interface, we generally call functions using
the plt module. These functions work with the
current Figure and Axes.
In the Object-Oriented API, we create Figure and Axes objects and call methods directly on those objects.
Pyplot Code
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 30])
plt.title('Sales Report')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()
Object-Oriented Code
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
ax.set_title('Sales Report')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')
plt.show()
Both programs create a similar chart. The second program uses an explicit Axes object to control the chart.
3. Why Do We Transition to the Object-Oriented API?
The pyplot interface is convenient for simple charts. However, when an application contains multiple figures, multiple subplots or complex visualizations, explicit object references make the code easier to manage.
| Reason | Explanation |
|---|---|
| Better Control | Each Axes object can be customized independently. |
| Code Organization | Figure-level and Axes-level operations are clearly separated. |
| Multiple Charts | Different Axes objects can be accessed directly. |
| Reusability | Axes objects can be passed to functions. |
| Maintainability | Explicit object references make larger plotting programs easier to maintain. |
4. Mapping Pyplot Functions to Axes Methods
Many pyplot functions have corresponding Axes methods. During transition, we replace the pyplot function with the appropriate method of the Axes object.
| Pyplot Function | Object-Oriented Method | Purpose |
|---|---|---|
| plt.plot() | ax.plot() | Creates a line chart. |
| plt.scatter() | ax.scatter() | Creates a scatter plot. |
| plt.bar() | ax.bar() | Creates a bar chart. |
| plt.hist() | ax.hist() | Creates a histogram. |
| plt.title() | ax.set_title() | Sets the chart title. |
| plt.xlabel() | ax.set_xlabel() | Sets the X-axis label. |
| plt.ylabel() | ax.set_ylabel() | Sets the Y-axis label. |
| plt.xlim() | ax.set_xlim() | Sets X-axis limits. |
| plt.ylim() | ax.set_ylim() | Sets Y-axis limits. |
| plt.legend() | ax.legend() | Displays a legend. |
| plt.grid() | ax.grid() | Controls grid lines. |
| plt.xticks() | ax.set_xticks() | Sets X-axis tick positions. |
| plt.yticks() | ax.set_yticks() | Sets Y-axis tick positions. |
5. Understanding Figure-Level Methods
Not every pyplot operation belongs to an Axes object. Some operations control the entire Figure.
When transitioning code, use Figure methods for operations related to the overall figure.
| Figure Operation | Object-Oriented Method | Purpose |
|---|---|---|
| Create Figure | plt.subplots() | Creates a Figure and Axes objects. |
| Overall Title | fig.suptitle() | Sets the overall Figure title. |
| Figure Size | fig.set_size_inches() | Changes Figure dimensions. |
| Save Figure | fig.savefig() | Saves the Figure to a file. |
| Figure Layout | fig.tight_layout() | Adjusts spacing between figure elements. |
| Subplot Spacing | fig.subplots_adjust() | Adjusts subplot margins and spacing. |
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.set_size_inches(9, 5)
fig.suptitle('Company Report')
ax.plot([1, 2, 3, 4], [100, 150, 130, 200])
ax.set_title('Monthly Sales')
fig.tight_layout()
plt.show()
Output
Figure displayed with:
- Overall title: Company Report.
- Axes title: Monthly Sales.
- Figure size: 9 x 5 inches.
- Line chart containing four data points.
- Adjusted figure layout.
6. Steps to Transition Pyplot Code
Follow these steps when converting a pyplot-based program into the Object-Oriented API.
General steps for transitioning from pyplot functions to Object-Oriented methods.
- Import Matplotlib using pyplot.
- Create Figure and Axes using
plt.subplots(). - Replace plotting functions with Axes methods.
- Replace title and label functions with Axes setter methods.
- Move Figure-level settings to Figure methods.
- Test the converted chart and verify its appearance.
7. Transitioning a Line Chart
Let's start by converting a simple pyplot line chart into the Object-Oriented API.
Original Pyplot Code
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 150, 130, 180, 220]
plt.plot(months, sales, marker='o')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.grid(True)
plt.show()
Converted Object-Oriented Code
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')
ax.set_title('Monthly Sales')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')
ax.grid(True)
plt.show()
Output
Monthly Sales line chart displayed.
- Five monthly sales values.
- Circular markers on the line.
- X-axis label: Month.
- Y-axis label: Sales.
- Grid lines enabled.
The main change is that plotting and formatting operations
now use the ax object.
8. Transitioning a Bar Chart
The same conversion technique can be used for bar charts.
Original Pyplot Code
import matplotlib.pyplot as plt
products = ['Laptop', 'Mobile', 'Tablet', 'Monitor']
sales = [45, 80, 35, 50]
plt.bar(products, sales)
plt.title('Product Sales')
plt.xlabel('Products')
plt.ylabel('Units Sold')
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
products = ['Laptop', 'Mobile', 'Tablet', 'Monitor']
sales = [45, 80, 35, 50]
fig, ax = plt.subplots()
ax.bar(products, sales)
ax.set_title('Product Sales')
ax.set_xlabel('Products')
ax.set_ylabel('Units Sold')
plt.show()
Output
Product Sales bar chart displayed.
- Laptop: 45 units.
- Mobile: 80 units.
- Tablet: 35 units.
- Monitor: 50 units.
The chart displays four bars with product names
on the X-axis and units sold on the Y-axis.
9. Transitioning a Scatter Plot
Scatter plots can also be converted by replacing
plt.scatter() with ax.scatter().
Original Pyplot Code
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6]
marks = [40, 50, 55, 65, 75, 90]
plt.scatter(study_hours, marks)
plt.title('Study Hours vs Marks')
plt.xlabel('Study Hours')
plt.ylabel('Marks')
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
study_hours = [1, 2, 3, 4, 5, 6]
marks = [40, 50, 55, 65, 75, 90]
fig, ax = plt.subplots()
ax.scatter(study_hours, marks)
ax.set_title('Study Hours vs Marks')
ax.set_xlabel('Study Hours')
ax.set_ylabel('Marks')
plt.show()
Output
Scatter plot displayed.
- Six data points.
- Study hours displayed on the X-axis.
- Marks displayed on the Y-axis.
- Title: Study Hours vs Marks.
10. Transitioning a Histogram
A histogram can be transitioned using the same approach.
Replace plt.hist() with ax.hist().
Original Pyplot Code
import matplotlib.pyplot as plt
marks = [45, 50, 55, 60, 65, 65, 70, 75, 80, 85, 90]
plt.hist(marks, bins=5)
plt.title('Student Marks Distribution')
plt.xlabel('Marks')
plt.ylabel('Frequency')
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
marks = [45, 50, 55, 60, 65, 65, 70, 75, 80, 85, 90]
fig, ax = plt.subplots()
ax.hist(marks, bins=5)
ax.set_title('Student Marks Distribution')
ax.set_xlabel('Marks')
ax.set_ylabel('Frequency')
plt.show()
Output
Histogram displayed with:
- Student marks grouped into five bins.
- Frequency shown on the Y-axis.
- Marks shown on the X-axis.
- Customized chart title and labels.
11. Transitioning Axis Limits and Tick Settings
Axis limits and tick positions can also be converted into Axes methods.
Original Pyplot Code
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y)
plt.xlim(0, 6)
plt.ylim(0, 60)
plt.xticks([1, 2, 3, 4, 5])
plt.yticks([0, 10, 20, 30, 40, 50, 60])
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 6)
ax.set_ylim(0, 60)
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([0, 10, 20, 30, 40, 50, 60])
plt.show()
Output
Line chart displayed with:
- X-axis limits from 0 to 6.
- Y-axis limits from 0 to 60.
- Custom X-axis tick positions.
- Custom Y-axis tick positions.
12. Transitioning Legends and Annotations
Legends and text annotations can also be managed directly through an Axes object.
Original Pyplot Code
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 30]
plt.plot(x, y, label='Sales')
plt.legend()
plt.text(3, 15, 'Sales Point')
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 30]
fig, ax = plt.subplots()
ax.plot(x, y, label='Sales')
ax.legend()
ax.text(3, 15, 'Sales Point')
plt.show()
Output
Line chart displayed with:
- Sales line.
- Legend displaying Sales.
- Text annotation at the specified coordinates.
13. Transitioning Multiple Subplots
One of the main advantages of the Object-Oriented API is that we can directly access each subplot through its Axes reference.
Original Pyplot Code
import matplotlib.pyplot as plt
plt.subplot(1, 2, 1)
plt.plot([1, 2, 3], [10, 20, 30])
plt.title('Sales')
plt.subplot(1, 2, 2)
plt.bar(['A', 'B', 'C'], [20, 30, 40])
plt.title('Profit')
plt.show()
Converted Object-Oriented Code
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
# First Axes
axes[0].plot([1, 2, 3], [10, 20, 30])
axes[0].set_title('Sales')
# Second Axes
axes[1].bar(['A', 'B', 'C'], [20, 30, 40])
axes[1].set_title('Profit')
fig.tight_layout()
plt.show()
Output
One Figure containing two charts:
1. Sales line chart.
2. Profit bar chart.
Each chart has its own Axes object and title.
plt.subplots() to access each chart directly.
14. Transitioning Figure Saving Methods
Saving a chart is a Figure-level operation. When using
the Object-Oriented API, use fig.savefig()
to save the specific Figure object.
Pyplot Approach
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 15, 30])
plt.title('Sales Chart')
plt.savefig('sales_chart.png')
plt.show()
Object-Oriented Approach
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title('Sales Chart')
fig.savefig('sales_chart.png', dpi=300, bbox_inches='tight')
plt.show()
Output
Chart displayed successfully.
Image file saved:
sales_chart.png
Save settings:
- Resolution: 300 DPI.
- Bounding box: tight.
The Object-Oriented approach makes it clear which Figure is being saved.
15. Creating Reusable Functions with Axes
We can pass an Axes object to a Python function. This makes it possible to create reusable plotting functions that can draw on an existing chart.
Example
import matplotlib.pyplot as plt
def create_sales_chart(ax, months, sales):
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()
months = ['Jan', 'Feb', 'Mar', 'Apr']
sales = [100, 150, 130, 200]
fig, ax = plt.subplots()
create_sales_chart(ax, months, sales)
fig.tight_layout()
plt.show()
Output
Monthly Sales chart displayed.
The reusable function:
- Draws the sales line.
- Sets the chart title.
- Adds axis labels.
- Enables grid lines.
- Displays the legend.
Passing Axes objects to functions is a useful technique when building larger applications and reusable chart components.
16. Complete Practical Conversion Example
Let's convert a small sales analysis program from pyplot into the Object-Oriented API.
Original Pyplot Program
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 140, 120, 180, 220]
profit = [20, 30, 25, 40, 55]
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(months, sales, marker='o', label='Sales')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.subplot(1, 2, 2)
plt.bar(months, profit, label='Profit')
plt.title('Monthly Profit')
plt.xlabel('Month')
plt.ylabel('Profit')
plt.legend()
plt.tight_layout()
plt.show()
Converted Object-Oriented Program
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 140, 120, 180, 220]
profit = [20, 30, 25, 40, 55]
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Sales chart
axes[0].plot(months, sales, marker='o', label='Sales')
axes[0].set_title('Monthly Sales')
axes[0].set_xlabel('Month')
axes[0].set_ylabel('Sales')
axes[0].legend()
axes[0].grid(True)
# Profit chart
axes[1].bar(months, profit, label='Profit')
axes[1].set_title('Monthly Profit')
axes[1].set_xlabel('Month')
axes[1].set_ylabel('Profit')
axes[1].legend()
fig.tight_layout()
plt.show()
Output
Sales Analysis Dashboard displayed.
First chart:
- Monthly Sales line chart.
- Five monthly sales values.
- Circular markers.
- Legend and grid lines.
Second chart:
- Monthly Profit bar chart.
- Five monthly profit values.
- Legend displayed.
Both charts are arranged horizontally in one Figure.
The converted program uses an explicit Axes reference for each chart. This makes the code easier to extend and maintain.
17. Common Mistakes and Solutions
| Common Mistake | Reason | Solution |
|---|---|---|
| Using plt.title() instead of ax.set_title() | Not updating the method for the Axes object. | Use the appropriate Axes method. |
| Using fig.plot() | Plotting methods belong to Axes, not Figure. | Use ax.plot(). |
| Confusing Figure and Axes | Both objects have different responsibilities. | Use Figure methods for the overall Figure and Axes methods for the plotting area. |
| Incorrect Axes indexing | Using the wrong subplot reference. | Check the dimensions of the Axes array. |
| Unexpected chart customization | Mixing current pyplot state with explicit Axes references. | Use consistent object references where possible. |
| Overlapping labels | Insufficient layout spacing. | Use fig.tight_layout() or adjust spacing. |
18. Best Practices for Transitioning Methods
- Create Figure and Axes objects at the beginning of the plotting code.
- Use Axes methods for plotting and chart customization.
- Use Figure methods for overall layout and saving.
- Replace pyplot functions carefully instead of performing a blind search-and-replace.
- Use explicit Axes references for multiple charts.
- Pass Axes objects to reusable plotting functions when needed.
- Keep the data processing logic separate from chart formatting.
- Test the converted program to verify that the chart remains correct.
19. Practice Questions
Basic Questions
- What does transitioning methods mean in Matplotlib?
- Why do developers convert pyplot code into the Object-Oriented API?
- What is the difference between plt.plot() and ax.plot()?
- Which method replaces plt.title()?
- Which method is used to set X-axis limits?
- What is the purpose of fig.savefig()?
- Which object is used to control the overall Figure layout?
Practical Questions
- Convert a pyplot line chart into the Object-Oriented API.
- Convert a bar chart using ax.bar().
- Convert a scatter plot using ax.scatter().
- Convert a histogram using ax.hist().
- Replace plt.xlim() and plt.ylim() with Axes methods.
- Convert a two-subplot pyplot program.
- Create a reusable function that accepts an Axes object.
- Save a Figure using fig.savefig().
Summary
Transitioning methods in Matplotlib means converting plotting code from the pyplot interface to the Object-Oriented API. The process involves creating Figure and Axes objects and replacing pyplot functions with appropriate object methods.
Common conversions include plt.plot() to ax.plot(), plt.bar() to ax.bar(), plt.title() to ax.set_title(), plt.xlabel() to ax.set_xlabel() and plt.ylabel() to ax.set_ylabel(). Axis limits, ticks, legends and grid settings can also be managed through Axes methods.
Figure-level operations such as setting the overall title, changing figure dimensions, adjusting layout and saving the chart should be handled through Figure methods.
The Object-Oriented API makes it easier to manage multiple charts, create reusable plotting functions and organize complex visualization programs. It is especially useful when developing dashboards and larger data visualization applications.