Chapter 6 – Object-Oriented Interface in Matplotlib
Until now, we’ve been using Matplotlib in its simplest form — through the pyplot interface. While this is great for quick visualizations, it becomes difficult to manage when we start working with multiple plots, subplots, or customized figure layouts. That’s where the Object-Oriented Interface (OOI) of Matplotlib comes into play.
✅ Why Learn the Object-Oriented Interface?
The OO approach gives you complete control over every part of a figure — from axes and ticks to legends and titles. It’s the standard way professionals create complex and highly customized visualizations in Matplotlib.
In this chapter, you’ll learn:
- What the Object-Oriented Interface is and why it’s important
- How to create
FigureandAxesobjects - How to draw plots using
ax.plot()and related methods - How to handle multiple subplots efficiently
- How to customize each part of your plot through objects
✅ The Two Ways to Use Matplotlib
Matplotlib provides two main approaches for creating plots:
- Pyplot Interface (state-based): Quick and convenient for small scripts.
- Object-Oriented Interface: Recommended for large, structured projects or dashboards.
In the pyplot style, you usually do something like this:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Simple Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
This works fine, but you have limited control when you need to handle multiple axes, or when you want to integrate Matplotlib with frameworks like Tkinter, Flask, or Dash.
In contrast, the Object-Oriented Interface gives you more structured control:
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("Simple Plot (OOI)")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
plt.show()
✅ Understanding Figures and Axes
Matplotlib visualizations are built around two main objects:
- Figure — The overall container that holds everything, including one or more subplots (axes).
- Axes — The actual plotting area where data is drawn (each plot has its own axes).
Think of it like this:
Figure→ The page of a book.Axes→ A single drawing inside that page.
✅ Creating Figures and Axes
The most common way to create them is using plt.subplots():
fig, ax = plt.subplots()
This returns a Figure object (fig) and an Axes object (ax), which you can now control independently.
✅ Adding Multiple Axes (Subplots)
You can create multiple axes at once using plt.subplots(rows, cols):
fig, ax = plt.subplots(2, 2)
This creates a 2×2 grid of subplots and returns a 2D array of Axes objects. You can access them like this:
ax[0, 0].plot([1, 2, 3], [1, 4, 9])
ax[0, 1].plot([1, 2, 3], [2, 4, 6])
ax[1, 0].plot([1, 2, 3], [3, 6, 9])
ax[1, 1].plot([1, 2, 3], [4, 8, 12])
plt.tight_layout()
plt.show()
✅ Using Axes Methods
Every Axes object has several methods that correspond to pyplot functions, for example:
ax.plot()→ draw line plotsax.bar()→ bar chartsax.hist()→ histogramsax.scatter()→ scatter plotsax.set_title(),ax.set_xlabel(),ax.set_ylabel()→ set labels
Let’s see how a complete chart looks using the OO interface:
fig, ax = plt.subplots()
ax.plot([0, 1, 2, 3], [10, 20, 25, 30], label="Growth")
ax.set_title("Company Growth Over Time")
ax.set_xlabel("Year")
ax.set_ylabel("Revenue (in Millions)")
ax.legend()
plt.show()
✅ Controlling Figure Size and Layout
To change the figure size, pass the figsize parameter in plt.subplots():
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3], [10, 20, 30])
plt.show()
This makes the chart more readable and properly scaled for reports or dashboards.
✅ Adding Multiple Plots to the Same Axes
Unlike plt.plot(), you can call ax.plot() multiple times on the same axes to draw multiple lines:
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 6], label="Line 1")
ax.plot([1, 2, 3], [1, 3, 5], label="Line 2")
ax.legend()
plt.show()
✅ Setting Titles and Labels
In the OO interface, you’ll always use the set_ prefix:
ax.set_title("Sales Report 2024")
ax.set_xlabel("Months")
ax.set_ylabel("Sales (in units)")
This approach is cleaner and avoids interference between multiple figures.
✅ Combining Multiple Figures
You can even open and manage multiple figure windows using the OO interface:
fig1, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [10, 20, 30])
ax1.set_title("First Figure")
fig2, ax2 = plt.subplots()
ax2.plot([1, 2, 3], [5, 10, 15])
ax2.set_title("Second Figure")
plt.show()
This is particularly useful for comparing datasets or visualizing different experiments side by side.
✅ Example: Multiple Axes with Shared X or Y
Matplotlib allows you to create shared axes using parameters like sharex or sharey:
fig, ax = plt.subplots(2, 1, sharex=True)
ax[0].plot([1, 2, 3], [10, 20, 30])
ax[1].plot([1, 2, 3], [30, 20, 10])
ax[0].set_title("Shared X-Axis Example")
plt.show()
This ensures both plots share the same X scale, making comparison easier.
✅ Adding Texts and Annotations
You can annotate specific points in your plot using ax.text() or ax.annotate() methods:
fig, ax = plt.subplots()
ax.plot([10, 20, 30], [5, 10, 15])
ax.text(20, 10, "Midpoint", fontsize=12, color="red")
ax.annotate("Highest", xy=(30, 15), xytext=(25, 17),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
✅ OO vs Pyplot Summary
| Aspect | Pyplot | Object-Oriented |
|---|---|---|
| Ease of Use | Simple for small scripts | Best for structured programs |
| Control | Limited | Full control over layout and objects |
| Multiple Figures | Harder to manage | Easy and independent |
| Integration | Basic | Great for dashboards, GUIs, etc. |
✅ Best Practices
- Always use
fig, ax = plt.subplots()for new projects. - Use meaningful variable names for figures and axes.
- Apply
plt.tight_layout()to prevent label overlap. - Keep each figure focused on one concept.
✅ Summary
In this chapter, you learned that the Object-Oriented Interface (OOI) is the professional way to work with Matplotlib. It helps you separate your visualization logic, manage multiple figures, and gain full control over every plot element.
In the next chapter, we’ll move further into Advanced Customization — exploring annotations, text placement, tick formatting, and more refined styling to make your charts presentation-ready.
