🎨 Matplotlib: Shapes and Visual Control
The Art Studio Analogy
Imagine you’re an artist with a magical canvas. You can draw lines to guide your work, add colorful shapes, layer them like stickers, and even cut parts that go outside your frame. That’s exactly what Matplotlib lets you do with data!
📏 Reference Lines and Spans
What Are Reference Lines?
Think of drawing a straight line across your paper to show “this is the important level.” That’s a reference line!
Horizontal Lines go left ↔ right:
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.plot([1, 2, 3, 4], [2, 4, 1, 3])
# Draw a line at y=2.5
plt.axhline(y=2.5, color='red',
linestyle='--', label='Target')
plt.legend()
plt.show()
Vertical Lines go up ↕ down:
# Draw a line at x=2
plt.axvline(x=2, color='green',
linestyle=':', linewidth=2)
What Are Spans?
Spans are like highlighting a section with a marker. Instead of a line, you shade an entire area!
Horizontal Span - shade between two y-values:
# Shade the "safe zone" between y=1 and y=3
plt.axhspan(1, 3, alpha=0.3,
color='yellow', label='Safe Zone')
Vertical Span - shade between two x-values:
# Mark the "weekend" from x=5 to x=7
plt.axvspan(5, 7, alpha=0.2,
color='blue', label='Weekend')
🎯 Real-Life Uses
| Use Case | Type | Example |
|---|---|---|
| Budget limit | axhline |
Show $500 spending cap |
| Deadline | axvline |
Mark due date on timeline |
| Danger zone | axhspan |
Highlight unsafe temperature range |
| Holiday period | axvspan |
Shade vacation days |
đź”· Adding Shapes to Plot
Basic Shapes with Simple Commands
You can add shapes directly to any plot using plt functions:
Rectangles:
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
ax.plot([0, 10], [0, 10])
# Add a rectangle
rect = Rectangle((2, 2), 3, 4,
color='coral', alpha=0.7)
ax.add_patch(rect)
plt.show()
The rectangle starts at (2, 2), is 3 units wide, and 4 units tall.
Circles:
from matplotlib.patches import Circle
circle = Circle((5, 5), radius=1.5,
color='skyblue', alpha=0.8)
ax.add_patch(circle)
Ellipses:
from matplotlib.patches import Ellipse
ellipse = Ellipse((5, 5), width=4, height=2,
angle=30, color='pink')
ax.add_patch(ellipse)
The angle rotates the ellipse!
🎠Patch Artists
What is a Patch?
A “patch” is Matplotlib’s word for any 2D shape. Think of patches like stickers you can customize and stick on your plot!
Common Patch Types
graph TD A["Patch Artists"] --> B["Rectangle"] A --> C["Circle"] A --> D["Ellipse"] A --> E["Polygon"] A --> F["Wedge"] A --> G["FancyBboxPatch"] A --> H["Arrow"]
Creating Custom Polygons
Draw any shape by listing corner points:
from matplotlib.patches import Polygon
# Triangle corners: (1,1), (3,4), (5,1)
triangle = Polygon(
[(1, 1), (3, 4), (5, 1)],
closed=True,
facecolor='gold',
edgecolor='black',
linewidth=2
)
ax.add_patch(triangle)
Fancy Box Patches
Create beautiful boxes with rounded corners:
from matplotlib.patches import FancyBboxPatch
fancy = FancyBboxPatch(
(1, 1), 3, 2,
boxstyle="round,pad=0.1,rounding_size=0.5",
facecolor='lightgreen',
edgecolor='darkgreen'
)
ax.add_patch(fancy)
Wedges (Pie Slices)
from matplotlib.patches import Wedge
# Center (5,5), radius 2, from 45° to 135°
wedge = Wedge((5, 5), 2, 45, 135,
color='orange')
ax.add_patch(wedge)
📚 Z-Order Layer Control
The Stacking Problem
When you draw multiple things, some might hide others. Z-order controls what’s on top.
Think of it like stacking papers:
- Lower z-order = paper at the bottom
- Higher z-order = paper on top
Default Z-Order Values
| Element | Default Z-Order |
|---|---|
| Patches | 1 |
| Lines | 2 |
| Text | 3 |
| Legend | 5 |
Setting Z-Order
fig, ax = plt.subplots()
# This circle has LOW z-order (behind)
circle1 = Circle((3, 3), 1.5,
color='red', zorder=1)
ax.add_patch(circle1)
# This circle has HIGH z-order (in front)
circle2 = Circle((4, 3), 1.5,
color='blue', zorder=3)
ax.add_patch(circle2)
# Line goes in middle
ax.plot([1, 6], [3, 3], 'k-',
linewidth=5, zorder=2)
ax.set_xlim(0, 7)
ax.set_ylim(0, 6)
plt.show()
🎯 Visual Result
Blue circle (z=3) → TOP
Black line (z=2) → MIDDLE
Red circle (z=1) → BOTTOM
✂️ Clipping
What is Clipping?
Clipping is like cutting out parts that go outside a frame. It’s like using scissors to trim a photo to fit a picture frame!
Automatic Clipping
By default, Matplotlib clips (hides) anything that goes outside your axes:
fig, ax = plt.subplots()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
# This circle extends past the edge
big_circle = Circle((9, 5), 3, color='purple')
ax.add_patch(big_circle)
# Part outside 0-10 range is CUT OFF!
Turning OFF Clipping
Sometimes you WANT shapes to overflow:
# clip_on=False lets it escape!
big_circle = Circle((9, 5), 3,
color='purple',
clip_on=False)
ax.add_patch(big_circle)
Custom Clip Paths
You can clip to ANY shape, not just the axes rectangle:
from matplotlib.patches import Circle, Rectangle
fig, ax = plt.subplots()
# Create a circular "window"
clip_circle = Circle((5, 5), 3)
# Draw a rectangle
rect = Rectangle((2, 2), 6, 6,
color='coral')
rect.set_clip_path(clip_circle,
transform=ax.transData)
ax.add_patch(rect)
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()
The rectangle is visible only inside the circular “window”!
đź§ Summary Flow
graph TD A["Start with Plot"] --> B{Need Guidelines?} B -->|Yes| C["Add axhline/axvline"] B -->|Yes| D["Add axhspan/axvspan"] B -->|No| E{Need Shapes?} E -->|Yes| F["Choose Patch Type"] F --> G["Rectangle/Circle/Polygon"] G --> H{Overlap Issues?} H -->|Yes| I["Adjust zorder"] I --> J{Shape Outside Frame?} J -->|Hide it| K["clip_on=True"] J -->|Show it| L["clip_on=False"] J -->|Custom| M["set_clip_path"]
🎮 Quick Reference
| Task | Code |
|---|---|
| Horizontal line | plt.axhline(y=5) |
| Vertical line | plt.axvline(x=3) |
| Shade y-range | plt.axhspan(2, 4) |
| Shade x-range | plt.axvspan(1, 3) |
| Add rectangle | ax.add_patch(Rectangle(...)) |
| Add circle | ax.add_patch(Circle(...)) |
| Bring to front | zorder=10 |
| Send to back | zorder=0 |
| Allow overflow | clip_on=False |
| Custom clip | shape.set_clip_path(...) |
🚀 You Did It!
Now you can:
- âś… Draw reference lines and shaded regions
- âś… Add circles, rectangles, and custom polygons
- âś… Control which shapes appear on top
- âś… Clip or reveal shapes beyond your plot boundaries
You’re becoming a Matplotlib artist! 🎨
