Skip to content

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

Published on

Updated on

Seaborn vs Matplotlib compared with runnable Python examples, customization and performance trade-offs, and how to combine both cleanly using ax= subplots.

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

DimensionSeabornMatplotlib
Abstraction levelHigh-level statistical visualization APILow-level, general-purpose 2D/3D plotting engine
Best suited forEDA, statistical distributions, grouped comparisons, heatmapsPublication-grade figures, custom grids, annotations, animations
Default aestheticsClean palettes, readable spacing, automatic legendsBasic defaults; requires style sheets or manual tuning
Primary data inputTidy pandas DataFrames (data=df, x=..., y=..., hue=...)NumPy arrays, Python lists, or Series
Built-in statisticsBootstrapped CIs, KDE smoothing, linear/lowess fits, clusteringNone built in (compute manually with NumPy/SciPy)
Customization depthMedium natively; full access via underlying Matplotlib AxesComplete control over every spine, tick, patch, and transform
Large-dataset speedSlower when computing KDE/CI aggregations on 50k+ rowsFaster raw rendering; supports rasterized=True and collections
Learning curveFaster for common charts; subtle figure-level vs axes-level rulesSteeper initially; two APIs (pyplot vs object-oriented Axes)
Trending reads

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 an ax= argument and return a standard matplotlib.axes.Axes object. They drop cleanly into any plt.subplots() grid.
  • Figure-level functions (sns.relplot, sns.displot, sns.catplot, sns.lmplot, sns.pairplot) create and own their own FacetGrid or PairGrid figure. You cannot pass ax= to them; instead, you customize them through the returned grid object (g.set_axis_labels(...), g.figure.suptitle(...)).

Matplotlib visualization library overview

Seaborn statistical visualization library overview

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 existing plt.subplots() layout. Trying to pass ax= raises a TypeError or 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, and FuncAnimation.

Performance on Large Datasets

  • Seaborn overhead: Functions like sns.lineplot, sns.barplot, and sns.pointplot compute bootstrapped confidence intervals by default (errorbar=("ci", 95)), which can take seconds on 100k+ rows. Pass errorbar=None or pre-aggregate with pandas (df.groupby(...).mean()) to recover speed.
  • Matplotlib speed: Direct ax.plot() and ax.scatter() skip statistical estimation. For 100k+ points in PDF/SVG output, pass rasterized=True to 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 GoalPickWhy
Explore a new pandas DataFrame quicklySeabornMinimal code, tidy data= / hue= syntax, clean defaults
Correlation matrix, pair plot, or regression with CISeabornSingle-call statistical primitives (heatmap, pairplot, regplot)
Multi-panel dashboard or academic journal figureBoth (plt.subplots + ax=)Matplotlib manages exact layout/DPI; Seaborn draws statistical panels
Dual axes, custom annotations, radar/polar, or animationsMatplotlibDirect access to every artist, transform, and formatter
100k+ rows or low-latency automated chart generationMatplotlibAvoids 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