By the end of this lesson, you will be able to generate five essential data visualizations using Matplotlib and Seaborn: line, bar, histogram, scatter, and heatmap plots.
What it is
Matplotlib is a foundational plotting library for Python that provides low-level control over figure creation. Seaborn is built on top of Matplotlib, offering a high-level interface with attractive default styles and statistical functions. Together, they allow data scientists to quickly explore distributions, relationships, and trends. Key terms includefigure (the canvas), axes (the plot area), and style (visual aesthetics).
Why it matters
- Rapid Exploration: Quickly identify outliers, trends, or patterns in raw data.
- Communication: Transform complex numerical results into intuitive visuals for stakeholders.
- Statistical Insight: Seaborn integrates statistical estimation directly into plots (e.g., confidence intervals).
- Customization: Matplotlib allows fine-grained control over labels, ticks, and colors when defaults are insufficient.
Syntax or steps
The standard workflow involves importing libraries, preparing data, creating a plot object, customizing it, and displaying or saving it. For Seaborn, you often pass a DataFrame directly to plotting functions likesns.lineplot(). For Matplotlib, you typically use plt.plot() or ax.bar(). Always call plt.show() to render the output in interactive environments.
Example
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# Generate sample data
np.random.seed(42)
df = pd.DataFrame({
'x': np.linspace(0, 10, 50),
'y': np.sin(np.linspace(0, 10, 50)) + np.random.normal(0, 0.1, 50),
'category': np.random.choice(['A', 'B'], 50)
})
# Set Seaborn style
sns.set_theme(style="whitegrid")
# Create a figure with subplots
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
# 1. Line Plot
axes[0, 0].plot(df['x'], df['y'], color='blue')
axes[0, 0].set_title('Line Plot')
# 2. Bar Plot
bar_data = df.groupby('category')['y'].mean()
axes[0, 1].bar(bar_data.index, bar_data.values, color=['green', 'orange'])
axes[0, 1].set_title('Bar Plot')
# 3. Histogram
axes[0, 2].hist(df['y'], bins=10, color='purple', alpha=0.7)
axes[0, 2].set_title('Histogram')
# 4. Scatter Plot
axes[1, 0].scatter(df['x'], df['y'], c=df['category'], cmap='viridis')
axes[1, 0].set_title('Scatter Plot')
# 5. Heatmap (Correlation Matrix)
corr_matrix = df[['x', 'y']].corr()
sns.heatmap(corr_matrix, annot=True, ax=axes[1, 1], cmap='coolwarm')
axes[1, 1].set_title('Heatmap')
# Hide unused subplot
axes[1, 2].axis('off')
plt.tight_layout()
plt.show()
This code creates a grid of plots. plt.subplots generates the figure and axes objects. Each axis is customized individually. Note how sns.heatmap is used within a Matplotlib axis context.
Common mistakes
- Forgetting
plt.show(): In scripts, plots may not appear without this command. - Mixing Styles Incorrectly: Calling
sns.set_theme()after creating plots can override previous customizations unexpectedly. - Ignoring Data Types: Passing non-numeric data to numeric plots (like histograms) causes errors; ensure columns are cast correctly.
- Crowded Labels: Failing to use
plt.tight_layout()often results in overlapping titles or cut-off tick labels.
When to use it
| Scenario | Recommended Tool | Reason |
|---|---|---|
| Quick statistical exploration | Seaborn | Built-in stats and beautiful defaults save time. |
| Complex custom layouts | Matplotlib | Provides granular control over every element. |
| Interactive web apps | Neither (use Plotly) | Matplotlib/Seaborn are static by default. |
Practice
Guided Exercise: Modify the example above to add a legend to the Scatter Plot showing categories A and B.Hint: Use
axes[1, 0].legend() after setting labels in the scatter call via label parameter or manually adding handles.
Challenge: Replace the Bar Plot with a Box Plot using Seaborn's sns.boxplot() function on the same data.Expected Output: A box plot showing the distribution of 'y' values grouped by 'category'.
Quick check
Question: Which function is primarily responsible for rendering the final image in a script? Answer:plt.show()