🎯 Matplotlib Annotations & Math: Adding Labels Like Sticky Notes!
The Big Picture: Your Plot’s Voice
Imagine you drew the most amazing picture ever. But wait! No one knows what they’re looking at. That’s where annotations come in – they’re like sticky notes you put on your drawing to say “Hey, look at THIS!”
And math expressions? They’re like writing fancy math homework directly on your picture – with symbols like π and √ that look super professional!
🏷️ Part 1: Annotations Basics
What is an Annotation?
Think of annotations like a tour guide pointing at something interesting. You’re walking through a museum, and the guide says: “Look here! This is important!”
In Matplotlib, we use annotate() to be that tour guide for our plots.
Your First Annotation
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
# Add a sticky note!
plt.annotate('Peak!',
xy=(5, 25), # Where to point
xytext=(4, 20), # Where the note sits
arrowprops=dict(arrowstyle='->'))
plt.show()
Breaking It Down
| Part | What It Means | Real-Life Example |
|---|---|---|
'Peak!' |
Your message | The words on your sticky note |
xy=(5, 25) |
Point TO here | Where your finger points |
xytext=(4, 20) |
Put text HERE | Where you stick the note |
arrowprops |
The arrow line | The line from note to spot |
Simple Flow of Annotation
graph TD A["📝 Write your text"] --> B["📍 Pick the point to highlight"] B --> C["📌 Choose where text goes"] C --> D["➡️ Add an arrow to connect"] D --> E["✨ Done! Your annotation appears"]
🎨 Part 2: Annotation Styling
Making Your Sticky Notes Pretty!
Plain notes are boring. Let’s make them POP! It’s like decorating your room – same room, but way cooler.
The Arrow Styles Menu
Think of arrow styles like choosing different kinds of pens:
# Simple arrow (like a pencil line)
arrowprops=dict(arrowstyle='->')
# Fancy arrow (like a marker)
arrowprops=dict(arrowstyle='-|>')
# Curvy arrow (like a brush stroke)
arrowprops=dict(arrowstyle='fancy',
connectionstyle='arc3,rad=0.3')
Available Arrow Styles
| Style Code | Looks Like | When to Use |
|---|---|---|
'->' |
Simple arrow → | Basic pointing |
'-|>' |
Filled triangle →▶ | Important stuff |
'<->' |
Double arrow ↔ | Comparisons |
'fancy' |
Curved fancy | Making it pretty |
'wedge' |
Thick wedge | Big emphasis |
Text Box Styling
Your sticky note can have a background color too!
plt.annotate('Important!',
xy=(3, 9),
xytext=(1, 15),
arrowprops=dict(arrowstyle='->'),
bbox=dict(
boxstyle='round',
facecolor='yellow',
alpha=0.8
)
)
Box Style Options
boxstyle |
Description |
|---|---|
'round' |
Rounded corners (friendly) |
'square' |
Sharp corners (serious) |
'circle' |
Circular bubble |
'rarrow' |
Arrow shape pointing right |
'larrow' |
Arrow shape pointing left |
Full Styling Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4], [1,4,2,3])
ax.annotate('Look Here!',
xy=(2, 4),
xytext=(3, 3),
fontsize=12,
fontweight='bold',
color='white',
arrowprops=dict(
arrowstyle='fancy',
color='purple',
connectionstyle='arc3,rad=0.2'
),
bbox=dict(
boxstyle='round,pad=0.3',
facecolor='purple',
edgecolor='gold',
linewidth=2
)
)
plt.show()
📐 Part 3: Mathematical Expressions
Writing Math That Looks Like a Textbook
Remember when your teacher wrote equations on the board? They used special symbols like:
- Fractions: ½
- Square roots: √
- Greek letters: α, β, π
- Powers: x²
Matplotlib can do ALL of that!
The Magic Dollar Signs
In Matplotlib, dollar signs are magic wrappers for math:
# Regular text
plt.title('Area = pi * r squared')
# Math text (pretty!)
plt.title(r'$Area = \pi \cdot r^2#x27;)
The r before the string means “raw” – it helps Python not get confused.
Common Math Symbols
| What You Want | Code | Result |
|---|---|---|
| Pi | \pi |
π |
| Square root | \sqrt{x} |
√x |
| Fraction | \frac{a}{b} |
a/b |
| Power | x^2 |
x² |
| Subscript | x_1 |
x₁ |
| Sum | \sum |
Σ |
| Infinity | \infty |
∞ |
| Greater/equal | \geq |
≥ |
| Multiply | \times |
× |
| Greek alpha | \alpha |
α |
Building Math Step by Step
Let’s write the famous formula: E = mc²
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5,
r'$E = mc^2#x27;,
fontsize=40,
ha='center')
plt.axis('off')
plt.show()
More Complex Example
The quadratic formula:
plt.text(0.5, 0.5,
r'$x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}#x27;,
fontsize=24,
ha='center')
Flow: How Math Gets Rendered
graph TD A["Write text with $ signs"] --> B["Matplotlib finds the $...quot;] B --> C["Sends to math engine"] C --> D["Converts to pretty symbols"] D --> E["Displays on your plot!"]
🎓 Part 4: LaTeX Rendering
The Ultimate Math Power Tool
LaTeX (pronounced “lay-tech” or “lah-tech”) is like the Rolls-Royce of math writing. Scientists and mathematicians use it to write beautiful documents.
Matplotlib can use the same LaTeX engine to make your math look publication-ready!
Enabling Full LaTeX
import matplotlib.pyplot as plt
# Turn on LaTeX power!
plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'serif'
# Now ALL text uses LaTeX
plt.title(r'The Famous $\int_0^\infty e^{-x} dx#x27;)
⚠️ Note: Full LaTeX needs LaTeX installed on your computer. The basic math (without
usetex=True) works everywhere!
Basic vs Full LaTeX
| Feature | Basic Math $...$ |
Full LaTeX |
|---|---|---|
| Needs installation | No | Yes (LaTeX) |
| Speed | Fast | Slower |
| Quality | Good | Perfect |
| All symbols | Most | Everything |
LaTeX Formatting Commands
# Bold math
r'$\mathbf{bold}#x27;
# Italic (default)
r'$italic#x27;
# Roman (upright)
r'$\mathrm{upright}#x27;
# Calligraphy
r'$\mathcal{FANCY}#x27;
Complex LaTeX Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title(r'$f(x) = \sin(x)#x27;, fontsize=16)
plt.xlabel(r'$x$ (radians)')
plt.ylabel(r'$\sin(x)#x27;)
# Add annotation with LaTeX
plt.annotate(
r'$\frac{d}{dx}\sin(x) = \cos(x)#x27;,
xy=(np.pi/2, 1),
xytext=(2, 0.5),
fontsize=12,
arrowprops=dict(arrowstyle='->')
)
plt.show()
LaTeX Special Environments
For multi-line equations:
# Aligned equations
equation = r'''$\begin{aligned}
a &= b + c \\
d &= e + f
\end{aligned}#x27;''
plt.text(0.5, 0.5, equation, ha='center')
🌟 Putting It All Together
The Complete Annotation Toolkit
graph TD subgraph "Your Annotation Toolkit" A["📝 Annotations"] --> B["Basic: Point & Label"] A --> C["Styled: Pretty Arrows & Boxes"] D["📐 Math Text"] --> E["Basic: $...$ symbols"] D --> F["LaTeX: Full power"] end B --> G["✨ Professional Plots!"] C --> G E --> G F --> G
Real-World Example: Complete Plot
import matplotlib.pyplot as plt
import numpy as np
# Create data
x = np.linspace(0, 4, 100)
y = x**2
# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y, 'b-', linewidth=2)
# Title with math
ax.set_title(r'$f(x) = x^2#x27;, fontsize=18)
# Styled annotation
ax.annotate(
r'Minimum at $x=0#x27;,
xy=(0, 0),
xytext=(1, 5),
fontsize=12,
arrowprops=dict(
arrowstyle='fancy',
color='green',
connectionstyle='arc3,rad=0.2'
),
bbox=dict(
boxstyle='round',
facecolor='lightgreen',
alpha=0.8
)
)
# Another annotation
ax.annotate(
r'$f(2) = 4#x27;,
xy=(2, 4),
xytext=(3, 8),
fontsize=11,
arrowprops=dict(arrowstyle='->')
)
ax.set_xlabel(r'$x#x27;)
ax.set_ylabel(r'$f(x)#x27;)
plt.grid(True, alpha=0.3)
plt.show()
🎁 Quick Reference
Annotation Cheat Code
plt.annotate(
'text', # Your message
xy=(x, y), # Arrow points here
xytext=(x2, y2), # Text sits here
arrowprops={}, # Arrow style
bbox={} # Text box style
)
Math Symbol Cheat Code
| I want… | I type… |
|---|---|
| Fraction | \frac{top}{bottom} |
| Square root | \sqrt{stuff} |
| Power | base^{power} |
| Subscript | base_{sub} |
| Greek | \alpha, \beta, \pi |
🎉 You Did It!
You now know how to:
- ✅ Add annotations to point out important stuff
- ✅ Style your annotations with arrows and boxes
- ✅ Write math expressions that look professional
- ✅ Use LaTeX for publication-quality math
Your plots are no longer silent pictures – they can speak to your audience!
Go ahead and annotate your next masterpiece! 🚀
