🎨 Plot Styling: Legends and Grids in Matplotlib
The Story of the Treasure Map 🗺️
Imagine you’re a pirate captain with a treasure map. The map shows three colored paths:
- A red path to Gold Island
- A blue path to Silver Bay
- A green path to Diamond Cave
But wait! Without labels, how would your crew know which path is which? And without grid lines, how would they measure distances?
That’s exactly what legends and grids do in Matplotlib!
- Legends = Labels that tell us what each line means
- Grids = The helpful lines that make reading easier
🏷️ Legend Basics
What is a Legend?
A legend is like a name tag for your plot lines. Just like how you wear a name tag at school so people know who you are, plot lines need legends so people know what they represent.
Your First Legend
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
cats = [2, 4, 6, 8, 10]
dogs = [1, 3, 5, 7, 9]
plt.plot(x, cats, label='Cats')
plt.plot(x, dogs, label='Dogs')
plt.legend()
plt.show()
What happened?
label='Cats'→ Gave the first line its namelabel='Dogs'→ Gave the second line its nameplt.legend()→ Said “Show me those names!”
Where Does the Legend Go?
graph TD A[plt.legend] --> B[loc parameter] B --> C[upper right - default] B --> D[upper left] B --> E[lower right] B --> F[lower left] B --> G[center] B --> H[best - auto picks]
Common Locations:
# Top right corner (default)
plt.legend(loc='upper right')
# Top left corner
plt.legend(loc='upper left')
# Bottom right
plt.legend(loc='lower right')
# Let Matplotlib decide
plt.legend(loc='best')
Pro tip: Use loc='best' and Matplotlib will find a spot that doesn’t cover your data!
✨ Legend Customization
Making Your Legend Pretty
Think of customization like decorating your room. You can change:
- The frame (border around it)
- The shadow (makes it pop!)
- The transparency (see through?)
- The columns (how it’s arranged)
Remove the Box
# No border around legend
plt.legend(frameon=False)
Add a Shadow
# Makes legend pop out
plt.legend(shadow=True)
Change Transparency
# Semi-transparent background
plt.legend(framealpha=0.5)
Multiple Columns
Got lots of items? Spread them out!
# Arrange in 2 columns
plt.legend(ncol=2)
Change the Font Size
# Bigger text
plt.legend(fontsize=12)
# Or use words
plt.legend(fontsize='large')
Complete Custom Legend Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
plt.plot(x, [1, 4, 9, 16], label='Squares')
plt.plot(x, [1, 8, 27, 64], label='Cubes')
plt.legend(
loc='upper left',
shadow=True,
framealpha=0.9,
fontsize=10,
title='Math Magic'
)
plt.show()
Adding a Title to Your Legend
plt.legend(title='My Data')
📏 Grid Customization
What is a Grid?
Remember graph paper from math class? Those little squares that help you draw straight lines and count boxes?
A grid in Matplotlib is exactly that! It adds helper lines so you can:
- Read values more easily
- See patterns clearly
- Make your plot look professional
Turn On the Grid
plt.grid(True)
That’s it! One line of code adds a grid.
Turn Off the Grid
plt.grid(False)
Which Lines Do You Want?
graph TD A[plt.grid] --> B[axis parameter] B --> C[both - all lines] B --> D[x - vertical only] B --> E[y - horizontal only]
# Only horizontal lines
plt.grid(axis='y')
# Only vertical lines
plt.grid(axis='x')
# Both (default)
plt.grid(axis='both')
Grid Style Options
Make your grid pretty!
# Dashed lines
plt.grid(linestyle='--')
# Dotted lines
plt.grid(linestyle=':')
# Dash-dot pattern
plt.grid(linestyle='-.')
Grid Color
# Light gray grid
plt.grid(color='gray')
# Light blue grid
plt.grid(color='lightblue')
Grid Transparency
# Faint grid lines
plt.grid(alpha=0.3)
# Strong grid lines
plt.grid(alpha=0.8)
Grid Line Thickness
# Thin lines
plt.grid(linewidth=0.5)
# Thick lines
plt.grid(linewidth=2)
Complete Grid Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
plt.plot(x, y, 'b-o')
plt.grid(
True,
linestyle='--',
color='gray',
alpha=0.5,
linewidth=0.7
)
plt.show()
🎯 Putting It All Together
Here’s a complete example with both legend AND grid:
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
apples = [10, 15, 13, 18, 20, 25]
oranges = [8, 12, 15, 14, 18, 22]
plt.plot(months, apples,
'r-o', label='Apples')
plt.plot(months, oranges,
'orange', label='Oranges')
# Add styled legend
plt.legend(
loc='upper left',
shadow=True,
fontsize=10
)
# Add styled grid
plt.grid(
linestyle='--',
alpha=0.5
)
plt.title('Fruit Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()
đź§ Quick Summary
| Feature | Code | What it does |
|---|---|---|
| Add legend | plt.legend() |
Shows labels |
| Position | loc='best' |
Moves legend |
| No frame | frameon=False |
Removes box |
| Shadow | shadow=True |
Adds shadow |
| Grid on | plt.grid(True) |
Shows grid |
| Grid style | linestyle='--' |
Dashed lines |
| Grid fade | alpha=0.5 |
Transparency |
🌟 Remember This!
- Labels come first → Use
label='name'when plotting - Then call legend → Use
plt.legend()to display - Grid is one line →
plt.grid(True)does the magic - Customize everything → Colors, styles, positions!
You’re now a legend and grid master! 🎉
Your plots will never be confusing again. Everyone will know exactly what each line means, and they’ll be able to read values easily with your helpful grids.
Happy plotting! 📊