Matplotlib Foundations: The Object-Oriented Interface
🎨 The Art Studio Analogy
Imagine you’re an artist with your own art studio. In this studio:
- The Figure is your canvas
- The Axes are the drawing areas on that canvas
- You are the artist controlling everything
Matplotlib gives you two ways to paint:
- Pyplot way – Like having an assistant who holds the brush for you
- OO (Object-Oriented) way – You hold the brush yourself with full control
Let’s explore why the OO way makes you a master artist!
🆚 OO vs Pyplot Comparison
The Story of Two Artists
Artist A (Pyplot User):
“Hey assistant, draw a line here!” “Now change the color!” “Wait, which canvas are we using?”
Artist B (OO User):
“I have my canvas. I have my brush. I know exactly what I’m doing.”
Why Does This Matter?
Think of it like cooking:
- Pyplot = Someone else controls the stove, you just say “add salt”
- OO = You control the stove, the pots, everything!
Code Comparison
Pyplot Way (Implicit):
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("My Plot")
plt.show()
OO Way (Explicit):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title("My Plot")
plt.show()
Key Differences
| Aspect | Pyplot | OO Interface |
|---|---|---|
| Control | Automatic | You decide |
| Multiple plots | Confusing | Crystal clear |
| Real projects | Tricky | Professional |
| Learning | Easy start | Better long-term |
When to Use Which?
graph TD A[What are you making?] --> B{Quick test?} B -->|Yes| C[Pyplot is fine] B -->|No| D{Multiple plots?} D -->|Yes| E[Use OO!] D -->|No| F{Real project?} F -->|Yes| E F -->|No| C
Simple Rule:
- Quick test in notebook? → Pyplot
- Anything else? → OO Interface
📍 Current Figure and Axes
The Invisible Pointer
When you use Pyplot, there’s an invisible pointer that keeps track of:
- Which canvas (Figure) you’re working on
- Which drawing area (Axes) you’re using
It’s like having a cursor you can’t see!
Finding What’s Current
import matplotlib.pyplot as plt
# Create a figure
plt.figure()
# Get the current figure
current_fig = plt.gcf()
print(f"Figure: {current_fig}")
# Get the current axes
current_ax = plt.gca()
print(f"Axes: {current_ax}")
gcf() = Get Current Figure gca() = Get Current Axes
Why This Gets Confusing
Imagine you have two canvases:
import matplotlib.pyplot as plt
# Canvas 1
plt.figure(1)
plt.plot([1, 2], [1, 2])
# Canvas 2
plt.figure(2)
plt.plot([1, 2], [2, 1])
# Which one is "current" now?
# Answer: Figure 2!
The invisible pointer moved to Figure 2.
The OO Solution: No Confusion!
import matplotlib.pyplot as plt
# You control everything explicitly
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
# Clear who is who!
ax1.plot([1, 2], [1, 2])
ax1.set_title("Canvas 1")
ax2.plot([1, 2], [2, 1])
ax2.set_title("Canvas 2")
Visual Flow
graph TD A[plt.subplots] --> B[Returns fig, ax] B --> C[fig = Your Canvas] B --> D[ax = Your Drawing Area] C --> E[Use fig for canvas stuff] D --> F[Use ax for drawing stuff]
Remember This!
| Function | Returns | Purpose |
|---|---|---|
plt.gcf() |
Figure | Get current canvas |
plt.gca() |
Axes | Get current drawing area |
plt.subplots() |
fig, ax | Create & get both! |
🧹 Clearing and Closing Figures
The Cleanup Crew
After painting, you need to:
- Clear the canvas (erase and reuse)
- Close the canvas (throw it away)
Clearing: Start Fresh
Clear the drawing area (Axes):
ax.clear() # Erases everything on ax
Clear the entire canvas (Figure):
fig.clf() # clf = Clear Figure
Real Example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Draw something
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title("First Drawing")
# Oops! Want to start over?
ax.clear()
# Draw something new
ax.plot([1, 2, 3], [9, 4, 1])
ax.set_title("Second Drawing")
plt.show()
Closing: Free Memory
Every figure uses computer memory. Too many open figures = slow computer!
# Close current figure
plt.close()
# Close specific figure
plt.close(fig)
# Close figure by number
plt.close(1)
# Nuclear option: close ALL figures
plt.close('all')
When to Clear vs Close
graph TD A[Done with figure?] --> B{Need it again?} B -->|Yes| C[Clear it: ax.clear] B -->|No| D[Close it: plt.close] D --> E[Memory freed!] C --> F[Same figure, fresh start]
The Complete Cleanup Example
import matplotlib.pyplot as plt
# Create figure
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 2, 3])
plt.show()
# Clear axes, reuse figure
ax.clear()
ax.plot([3, 2, 1], [1, 2, 3])
plt.show()
# All done? Close it!
plt.close(fig)
Memory Warning!
Problem:
# Creating 100 figures without closing!
for i in range(100):
fig, ax = plt.subplots()
ax.plot([1, 2], [i, i+1])
plt.show()
# Your computer: 😰
Solution:
# Close after each one!
for i in range(100):
fig, ax = plt.subplots()
ax.plot([1, 2], [i, i+1])
plt.show()
plt.close(fig) # Free memory!
# Your computer: 😊
🎯 Quick Reference
The Big Picture
| What | Pyplot | OO Interface |
|---|---|---|
| Create | plt.figure() |
fig, ax = plt.subplots() |
| Get Figure | plt.gcf() |
Already have fig |
| Get Axes | plt.gca() |
Already have ax |
| Clear Axes | plt.cla() |
ax.clear() |
| Clear Figure | plt.clf() |
fig.clf() |
| Close | plt.close() |
plt.close(fig) |
Your New Best Friends
# The OO starter pack
fig, ax = plt.subplots() # Create
ax.plot(x, y) # Draw
ax.set_title("Title") # Label
plt.show() # Display
plt.close(fig) # Cleanup
🚀 Why OO Makes You Powerful
- No confusion – You always know which figure/axes you’re using
- Multiple plots – Handle many figures without headaches
- Professional code – What real data scientists use
- Better debugging – Easy to find problems
- Memory control – You decide when to clean up
💡 Final Wisdom
“The Pyplot way is like driving automatic. The OO way is like driving manual. Both get you there, but manual gives you full control when you need it!”
Start with OO. Your future self will thank you!
Remember:
fig= Your canvasax= Your drawing area- Always
plt.close()when done!