15 min read
Visualization I: Matplotlib/Seaborn
Deep dive into static plotting with Python's core visualization libraries
What You'll Learn
- Matplotlib anatomy (Figure vs Axes)
- Customizing plots (titles, labels, colors)
- Subplots
- Seaborn themes and styles
- Saving figures
Matplotlib Basics
Matplotlib is the grandfather of Python plotting. It's powerful but verbose.
The Object-Oriented Interface (Recommended):
code.py
import matplotlib.pyplot as plt
# Create Figure and Axes
fig, ax = plt.subplots(figsize=(10, 6))
# Plot data on Axes
ax.plot([1, 2, 3], [10, 20, 15], label='Trend A')
# Customize
ax.set_title('My Plot Title')
ax.set_xlabel('X Axis Label')
ax.set_ylabel('Y Axis Label')
ax.legend()
ax.grid(True)
# Show
plt.show()Subplots
Creating multiple plots in one figure.
code.py
# 1 row, 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
ax1.plot(x, y)
ax1.set_title('Plot 1')
ax2.scatter(x, y)
ax2.set_title('Plot 2')
plt.tight_layout() # Fix spacing
plt.show()Seaborn: Matplotlib Made Easy
Seaborn is built on top of Matplotlib. It looks better by default and handles Pandas DataFrames natively.
code.py
import seaborn as sns
# Set theme
sns.set_theme(style="whitegrid")
# Plot
sns.scatterplot(
data=df,
x='total_bill',
y='tip',
hue='sex',
style='time',
size='size'
)
plt.title('Complex Scatter Plot')
plt.show()Customizing Seaborn
Since Seaborn returns Matplotlib axes, you can use Matplotlib commands to tweak it.
code.py
ax = sns.barplot(x='day', y='total_bill', data=df)
# Customizing using Matplotlib
ax.set_title('Average Bill by Day', fontsize=16)
ax.set_xlabel('Day of Week')
plt.xticks(rotation=45)Saving Figures
code.py
plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')
plt.savefig('my_plot.pdf')Practice Exercise
Create a dashboard with 4 subplots visualizing the 'tips' dataset:
- Histogram of total_bill
- Scatter plot of bill vs tip
- Bar plot of day counts
- Box plot of bill by gender
Next Steps
Static plots are great, but interactive plots are the future. Let's learn Plotly!
Practice & Experiment
Test your understanding by running Python code directly in your browser. Try the examples from the article above!