Seaborn vs Matplotlib: When to Use Which (With Code Examples)
Published on
Updated on

The short answer: Use Seaborn for fast statistical charts directly from pandas DataFrames (distributions, regressions, categorical comparisons, correlation heatmaps). Use Matplotlib when you need fine-grained layout control, custom annotations, dual axes, animations, or high-speed rendering on large datasets.
Because Seaborn is built directly on top of Matplotlib, the most productive workflow in real projects is hybrid: create the figure and grid with Matplotlib (fig, ax = plt.subplots(...)), plot the statistical layer with Seaborn (ax=ax), and finish styling with Matplotlib's object-oriented API.
TL;DR Comparison: Seaborn vs Matplotlib
| Dimension | Seaborn | Matplotlib |
|---|---|---|
| Abstraction level | High-level statistical visualization API | Low-level, general-purpose 2D/3D plotting engine |
| Best suited for | EDA, statistical distributions, grouped comparisons, heatmaps | Publication-grade figures, custom grids, annotations, animations |
| Default aesthetics | Clean palettes, readable spacing, automatic legends | Basic defaults; requires style sheets or manual tuning |
| Primary data input | Tidy pandas DataFrames (data=df, x=..., y=..., hue=...) | NumPy arrays, Python lists, or Series |
| Built-in statistics | Bootstrapped CIs, KDE smoothing, linear/lowess fits, clustering | None built in (compute manually with NumPy/SciPy) |
| Customization depth | Medium natively; full access via underlying Matplotlib Axes | Complete control over every spine, tick, patch, and transform |
| Large-dataset speed | Slower when computing KDE/CI aggregations on 50k+ rows | Faster raw rendering; supports rasterized=True and collections |
| Learning curve | Faster for common charts; subtle figure-level vs axes-level rules | Steeper initially; two APIs (pyplot vs object-oriented Axes) |
- ty 1.0 Migration Guide: Move from mypy to ty and Fix the type: ignore Comments That Stop Working
- Best Agent Skills for Claude Code and Codex: What to Install and How to Audit a Repo First
- Claude Code Permissions Hardening: Block Writes Outside Your Repo, Deny Instead of Prompt, and Audit settings.local.json
- How to Convert Python to EXE: Runcell, PyInstaller, Nuitka, and cx_Freeze
- pandas 3.1 Upgrade Guide: Fix the inplace Pandas4Warning, Use df.select() and pd.col(), and Read CSVs Faster
- How to Upgrade to OpenCode 2.0: Migrate Your v1 Config, Plugins, and Sessions
- Qwen3.8 27B: Specs, Memory Requirements, and How to Run It
- Haiku pricing: Haiku 5.5 vs 4.5 vs GPT-6 Luna
- Python 3.15 Upgrade Guide: Install with uv, Use Lazy Imports, and Check Your Data Stack
- Claude Code Mods Tutorial: Build and Test Your First Mod, Plus 15 Community Examples
- How to Use Pi Coding Agent 1.0: Install, Connect a Model, and Run Your First Task
- How to Use Laya: Classify Text in a pandas DataFrame with the Open-Source Jev Alternative
- Claude Code Reads AGENTS.md Now: Setup, Loading Modes, and Sharing One File with Codex, OpenCode, and Cursor
- How to View Deleted Reddit Posts (2026 Guide): 5 Ways That Still Work
- GPT Image 2.5: How to Use It, Flare vs Sunburst, and API Pricing
- How to Use DeepSeek Harness: Install, Set Up, and Run Your First Agent
- Runcell Science: An Open Source Alternative to Claude Science for Research Workflows
- How to Make Mac Not Sleep: Keep Codex, Claude Code, and AI Agents Running
- OpenClaw vs ZeroClaw vs Pi Agent vs Nanobot: Which AI Agent Stack Should You Choose in 2026?
- Can Claude Code Analyze Jupyter Notebooks for Data Science? What It Actually Does
- Claude Code Routines: Why AI Agent Cron Jobs Matter
- Claude Code Desktop Bypass Permissions: How to Enable It
- How to Build Two Python Agents with Google’s A2A Protocol - Step by Step Tutorial
- Top 10 growing data visualization libraries in Python in 2025
How Seaborn Builds on Matplotlib
Seaborn does not replace Matplotlib—every Seaborn chart draws onto a Matplotlib Figure and Axes. Understanding the two kinds of Seaborn functions prevents 90% of layout frustration:
- Axes-level functions (
sns.scatterplot,sns.lineplot,sns.histplot,sns.boxplot,sns.heatmap,sns.regplot) accept anax=argument and return a standardmatplotlib.axes.Axesobject. They drop cleanly into anyplt.subplots()grid. - Figure-level functions (
sns.relplot,sns.displot,sns.catplot,sns.lmplot,sns.pairplot) create and own their ownFacetGridorPairGridfigure. You cannot passax=to them; instead, you customize them through the returned grid object (g.set_axis_labels(...),g.figure.suptitle(...)).


Side-by-Side Runnable Python Examples
All four examples below share one self-contained synthetic DataFrame so you can copy and run them locally with no external downloads.
First, create the shared dataset:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng(42)
n = 180
segments = rng.choice(["Starter", "Pro", "Enterprise"], size=n, p=[0.45, 0.35, 0.20])
spend = rng.uniform(50, 500, size=n)
noise = rng.normal(0, 35, size=n)
segment_boost = pd.Series(segments).map({"Starter": 0, "Pro": 65, "Enterprise": 140}).to_numpy()
df = pd.DataFrame({
"segment": segments,
"ad_spend": spend,
"revenue": 1.6 * spend + segment_boost + noise,
"sessions": (spend * 0.8 + rng.normal(0, 20, size=n)).clip(10),
"conversion_rate": np.clip(0.02 + 0.00012 * spend + rng.normal(0, 0.01, size=n), 0.005, 0.15),
})1. Scatter Plot with Linear Regression Line
Seaborn computes the linear fit and 95% confidence band in a single call:
fig, ax = plt.subplots(figsize=(7, 4.5))
sns.regplot(data=df, x="ad_spend", y="revenue", scatter_kws={"alpha": 0.6}, ax=ax)
ax.set_title("Ad Spend vs Revenue (Seaborn)")
plt.tight_layout()
plt.show()Matplotlib requires computing the regression slope and intercept manually with NumPy:
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.scatter(df["ad_spend"], df["revenue"], alpha=0.6, label="Accounts")
slope, intercept = np.polyfit(df["ad_spend"], df["revenue"], deg=1)
x_line = np.linspace(df["ad_spend"].min(), df["ad_spend"].max(), 100)
ax.plot(x_line, slope * x_line + intercept, color="tab:red", linewidth=2, label="Linear fit")
ax.set_title("Ad Spend vs Revenue (Matplotlib)")
ax.set_xlabel("ad_spend")
ax.set_ylabel("revenue")
ax.legend()
plt.tight_layout()
plt.show()Verdict: Seaborn saves boilerplate and adds uncertainty bands automatically. Matplotlib is better when you need to display a custom model curve (for example, a scikit-learn pipeline prediction) with exact styling.
2. Grouped Distribution (Histogram + Density Curve)
Seaborn handles grouping (hue), automatic legends, and kernel density estimates (kde=True) natively:
fig, ax = plt.subplots(figsize=(7, 4.5))
sns.histplot(data=df, x="revenue", hue="segment", kde=True, element="step", ax=ax)
ax.set_title("Revenue Distribution by Segment (Seaborn)")
plt.tight_layout()
plt.show()Matplotlib requires looping over groups, aligning bin edges manually, and building the legend yourself:
fig, ax = plt.subplots(figsize=(7, 4.5))
bins = np.linspace(df["revenue"].min(), df["revenue"].max(), 25)
for seg, group in df.groupby("segment"):
ax.hist(group["revenue"], bins=bins, alpha=0.45, label=seg, edgecolor="white")
ax.set_title("Revenue Distribution by Segment (Matplotlib)")
ax.set_xlabel("revenue")
ax.set_ylabel("Count")
ax.legend(title="segment")
plt.tight_layout()
plt.show()Verdict: For grouped histograms, box plots, and violin plots during exploratory analysis, Seaborn is substantially faster to write and less error-prone (shared bin edges are handled automatically).
3. Annotated Correlation Heatmap
Seaborn draws a labeled, color-scaled correlation matrix in one function call:
corr = df[["ad_spend", "revenue", "sessions", "conversion_rate"]].corr()
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1, ax=ax)
ax.set_title("Correlation Matrix (Seaborn)")
plt.tight_layout()
plt.show()Matplotlib uses imshow() plus manual tick labels, colorbar setup, and a nested loop for cell annotations:
corr = df[["ad_spend", "revenue", "sessions", "conversion_rate"]].corr()
labels = corr.columns.tolist()
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(corr.to_numpy(), cmap="coolwarm", vmin=-1, vmax=1)
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
ax.set_xticks(range(len(labels)), labels=labels, rotation=30, ha="right")
ax.set_yticks(range(len(labels)), labels=labels)
for i in range(len(labels)):
for j in range(len(labels)):
ax.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center", color="black")
ax.set_title("Correlation Matrix (Matplotlib)")
plt.tight_layout()
plt.show()Verdict: sns.heatmap is one of Seaborn's strongest wins. Reach for Matplotlib's imshow only when rendering raw image tensors or custom non-uniform grids.
4. Multi-Panel Figure: Combining Seaborn and Matplotlib with ax=
The cleanest production pattern is letting Matplotlib control the figure canvas, figure size, and subplot grid, while Seaborn draws the statistical layers into individual Axes:
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), layout="constrained")
# Left panel: Seaborn boxplot + strip overlay
sns.boxplot(data=df, x="segment", y="revenue", order=["Starter", "Pro", "Enterprise"], ax=axes[0])
sns.stripplot(
data=df,
x="segment",
y="revenue",
order=["Starter", "Pro", "Enterprise"],
color="black",
alpha=0.3,
size=3,
ax=axes[0],
)
axes[0].set_title("Revenue Spread by Segment")
axes[0].set_xlabel("")
axes[0].set_ylabel("Revenue ($)")
# Right panel: Seaborn scatter + Matplotlib target threshold & annotation
sns.scatterplot(data=df, x="ad_spend", y="revenue", hue="segment", alpha=0.75, ax=axes[1])
axes[1].axhline(600, color="crimson", linestyle="--", linewidth=1.5)
axes[1].annotate(
"Target = $600",
xy=(75, 600),
xytext=(75, 720),
arrowprops={"arrowstyle": "->", "color": "crimson"},
color="crimson",
fontweight="bold",
)
axes[1].set_title("Spend Efficiency vs Target")
axes[1].set_xlabel("Ad Spend ($)")
axes[1].set_ylabel("")
fig.suptitle("Combined Seaborn + Matplotlib Workflow", fontsize=13, fontweight="bold")
plt.show()This hybrid pattern gives you Seaborn's speed for statistical encodings and Matplotlib's exact control for reference lines, arrows, titles, and layout spacing.
Customization, Performance, and Trade-Offs
Customization Limits
- Where Seaborn gets in the way: Figure-level functions (
displot,catplot,relplot) cannot be placed into an existingplt.subplots()layout. Trying to passax=raises aTypeErroror silently ignores the parameter depending on version. Use the axes-level counterpart (histplot,boxplot,scatterplot) whenever you control the grid. - Where Matplotlib shines: Dual y-axes (
ax.twinx()), custom tick formatters (FuncFormatter), broken axes, inset zoom boxes, vector PDF/SVG exports with exact millimeter sizing, andFuncAnimation.
Performance on Large Datasets
- Seaborn overhead: Functions like
sns.lineplot,sns.barplot, andsns.pointplotcompute bootstrapped confidence intervals by default (errorbar=("ci", 95)), which can take seconds on 100k+ rows. Passerrorbar=Noneor pre-aggregate with pandas (df.groupby(...).mean()) to recover speed. - Matplotlib speed: Direct
ax.plot()andax.scatter()skip statistical estimation. For 100k+ points in PDF/SVG output, passrasterized=Trueto keep vector text sharp while rasterizing the dense marker layer.
When Neither Static Library Is Ideal
Both Matplotlib and Seaborn render static images by default. If your goal is interactive exploratory analysis on a pandas DataFrame (filtering, switching chart types, drag-and-drop encoding in Jupyter without writing repetitive plotting code), tools like PyGWalker (opens in a new tab) or Plotly complement Matplotlib/Seaborn well—then switch back to Matplotlib/Seaborn when exporting final static charts for papers or slide decks.
Decision Matrix: Which Should You Choose?
| Your Goal | Pick | Why |
|---|---|---|
| Explore a new pandas DataFrame quickly | Seaborn | Minimal code, tidy data= / hue= syntax, clean defaults |
| Correlation matrix, pair plot, or regression with CI | Seaborn | Single-call statistical primitives (heatmap, pairplot, regplot) |
| Multi-panel dashboard or academic journal figure | Both (plt.subplots + ax=) | Matplotlib manages exact layout/DPI; Seaborn draws statistical panels |
| Dual axes, custom annotations, radar/polar, or animations | Matplotlib | Direct access to every artist, transform, and formatter |
| 100k+ rows or low-latency automated chart generation | Matplotlib | Avoids statistical aggregation overhead; supports rasterization |
FAQ
Is Seaborn better than Matplotlib?
Neither is universally better because Seaborn is built on Matplotlib. Seaborn is faster and cleaner for statistical charts on pandas DataFrames, while Matplotlib gives deeper control for custom layouts, annotations, and high-volume rendering.
Do I need to learn Matplotlib before Seaborn?
You can start creating charts with Seaborn immediately, especially for exploratory analysis. However, learning Matplotlib's core Figure and Axes concepts (fig, ax = plt.subplots(), ax.set_title(), ax.set_xlim(), fig.savefig()) is essential as soon as you need to customize labels, combine subplots, or export publication-ready figures.
Can I use Seaborn and Matplotlib in the same plot?
Yes. Create your figure and axes with fig, ax = plt.subplots(), pass ax=ax to any Seaborn axes-level function (such as sns.scatterplot, sns.boxplot, or sns.heatmap), and then call Matplotlib methods like ax.axhline(), ax.annotate(), or fig.savefig() on the same objects.
Why is Seaborn slower than Matplotlib on large DataFrames?
Seaborn runs statistical computations by default—such as 1,000-iteration bootstrapped confidence intervals in lineplot/barplot or kernel density estimation in kdeplot. Setting errorbar=None, pre-aggregating with pandas, or plotting directly with Matplotlib removes that overhead.
Related Guides
- Seaborn Heatmap Tutorial: Annotated Matrices and Colormaps
- Seaborn Color Palettes: Choose and Customize Themes
- Seaborn Histogram with histplot(): Bins, KDE, and Hue
- Matplotlib Subplots: Create Multi-Panel Figures with plt.subplots()
- Matplotlib figsize: Set Figure Size, DPI, Subplots & Pixel Conversion