Use Seaborn when you want a statistical chart straight from a DataFrame with little code, Matplotlib when you need full control over every element or publication-ready static files, and Plotly when the chart should be interactive (hover, zoom) or will live in a web page or dashboard. Seaborn is built on Matplotlib, so the two mix freely; Plotly is a separate system that draws in the browser. This post draws the same charts in all three so you can compare the code and the output. Versions used: Matplotlib 3.11, Seaborn 0.13.2, Plotly 7.2, pandas 3.1.
Quick Example
Simulated 5 km times for 60 runners on three training plans, timed every week for 12 weeks. The goal is one line per plan showing the average time with a 95% confidence band. The block runs on its own and draws the chart three times.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import seaborn as sns
# 60 runners on three training plans, timed over 5 km every week for 12 weeks
rng = np.random.default_rng(31)
plans = ["Intervals", "Long runs", "Mixed"]
gain = {"Intervals": 0.30, "Long runs": 0.16, "Mixed": 0.23} # minutes faster per week
rows = []
for i in range(60):
plan = plans[i % 3]
level = "Beginner" if i < 30 else "Experienced"
start = rng.normal(30 if level == "Beginner" else 26, 1.2)
rate = gain[plan] * (1.4 if level == "Beginner" else 0.7)
for week in range(13):
minutes = start - rate * week + rng.normal(0, 0.5)
rows.append((f"R{i + 1:02d}", plan, level, week, round(minutes, 2)))
df = pd.DataFrame(rows, columns=["runner", "plan", "level", "week", "minutes"])
# Matplotlib: aggregate yourself, then draw each line and band
summary = df.groupby(["plan", "week"])["minutes"].agg(["mean", "sem"]).reset_index()
fig, ax = plt.subplots(figsize=(7, 4))
for plan, g in summary.groupby("plan"):
ax.plot(g["week"], g["mean"], label=plan)
ax.fill_between(g["week"], g["mean"] - 1.96 * g["sem"], g["mean"] + 1.96 * g["sem"], alpha=0.2)
ax.set(xlabel="Week", ylabel="5 km time (minutes)", title="Matplotlib")
ax.legend(title="plan")
plt.show()
# Seaborn: one call does the averaging, the bands, the colors, and the legend
plt.figure(figsize=(7, 4))
ax = sns.lineplot(df, x="week", y="minutes", hue="plan")
ax.set(xlabel="Week", ylabel="5 km time (minutes)", title="Seaborn")
plt.show()
# Plotly Express: interactive, but you aggregate first and get error bars, not a band
fig = px.line(summary, x="week", y="mean", color="plan", error_y=1.96 * summary["sem"],
labels={"week": "Week", "mean": "5 km time (minutes)"}, title="Plotly")
fig.show()

All three show the same result: Intervals runners got about 3.8 minutes faster on average (28.2 to 24.4), Mixed runners 2.9 minutes, and Long runs runners 1.9 minutes. What differs is the work:
- Seaborn took one function call on the raw data. It grouped by week and plan, averaged, and bootstrapped a 95% confidence interval (
errorbar=("ci", 95)is the default since Seaborn 0.12). - Matplotlib needed a
groupbyand a loop: you compute the mean and interval, then draw each line withax.plot()and each band withax.fill_between(). Nothing happens that you didn't write. - Plotly Express also needs the summary table, since
px.linedoesn't aggregate. It haserror_y=for error bars but no confidence band option; a band takes a filledgo.Scattertrace. In return, the chart has hover, zoom, and clickable legend entries.
The later blocks reuse df, summary, and plans.
Matplotlib: Full Control Over Every Element
Matplotlib is the base layer of Python plotting. pandas' df.plot() and Seaborn both draw with it, and it saves PNG, SVG, PDF, and EPS files at an exact size and DPI. The cost is that you assemble the chart yourself. The payoff is that any detail can be changed, such as replacing the legend with labels at the end of each line:
colors = {"Intervals": "#d6336c", "Long runs": "#1c7ed6", "Mixed": "#5c940d"}
nudge = {"Intervals": 0, "Long runs": -7, "Mixed": 7} # points; two lines end close together
fig, ax = plt.subplots(figsize=(7, 4))
for plan, g in summary.groupby("plan"):
low, high = g["mean"] - 1.96 * g["sem"], g["mean"] + 1.96 * g["sem"]
ax.fill_between(g["week"], low, high, color=colors[plan], alpha=0.15, linewidth=0)
ax.plot(g["week"], g["mean"], color=colors[plan], linewidth=2.2)
last = g.iloc[-1]
ax.annotate(f"{plan}: {last['mean']:.1f} min", (last["week"], last["mean"]),
xytext=(8, nudge[plan]), textcoords="offset points", va="center",
color=colors[plan], fontweight="bold")
ax.spines[["top", "right"]].set_visible(False)
ax.set_xlim(0, 16) # leaves room for the labels
ax.set_xticks(range(0, 13, 2))
ax.set(xlabel="Week", ylabel="5 km time (minutes)")
ax.set_title("Average 5 km time by training plan, with 95% CI", loc="left")
fig.savefig("training-plans.pdf", bbox_inches="tight")
plt.show()

The Long runs and Mixed lines end only 0.25 minutes apart (25.6 and 25.8), so their labels are nudged 7 points up and down by hand. That kind of fix is routine in Matplotlib and awkward in the other two. Use the object-oriented fig, ax = plt.subplots() style shown here rather than plt.* calls once a chart has more than one panel; the Matplotlib tutorial covers the basics, and saving figures with savefig covers the export options.
Seaborn: Statistical Charts From a DataFrame
Seaborn takes long-format DataFrames and maps columns to x, y, hue, col, and row. It computes the statistics (means, confidence intervals, KDEs, regression fits) and handles colors and legends. Splitting the chart into one panel per experience level is one more argument with the figure-level sns.relplot():
g = sns.relplot(df, x="week", y="minutes", hue="plan", col="level", kind="line",
palette=colors, height=3.6, aspect=1.1)
g.set_titles("{col_name}")
g.set_axis_labels("Week", "5 km time (minutes)")
plt.show()

Beginners start near 30 minutes and improve nearly twice as fast (3.7 minutes over 12 weeks, against 2.1 for experienced runners, who start near 26). Every Seaborn function returns Matplotlib objects (an Axes, or a FacetGrid holding them), so anything from the Matplotlib section works on a Seaborn chart: ax.annotate(), ax.spines, fig.savefig(). The Seaborn lineplot post covers the errorbar options, and FacetGrid titles covers the panel labels.
Plotly: Interactive Charts for the Web
Plotly draws in the browser with plotly.js, so every chart is interactive by default and works in Jupyter, Dash, Streamlit, or a standalone HTML file. That matters most when there's too much to label. Here every runner gets their own line, and hovering shows which runner it is:
fig = px.line(df, x="week", y="minutes", color="plan", line_group="runner", facet_col="level",
hover_name="runner", color_discrete_map=colors,
labels={"week": "Week", "minutes": "5 km time (min)", "plan": "Plan"})
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_traces(opacity=0.6)
fig.update_layout(legend=dict(orientation="h", y=1.15, x=0, title=None))
fig.show()
Double-click a plan in the legend to isolate it, or drag a box to zoom into the last few weeks. facet_col="level" gives the same two panels as Seaborn's col=, and line_group="runner" draws one line per runner without giving each a separate color. For sharing, fig.write_html("chart.html", include_plotlyjs="cdn") writes a small file that loads plotly.js from a CDN. Static PNG, SVG, or PDF export uses Kaleido, which since version 1.0 needs a Chrome install (plotly_get_chrome downloads one). See Plotly line charts and Plotly facets for more.
The Same Grouped Box Plot in All Three
Box plots show how the APIs differ when there's a second grouping column. Here's the week 12 time by plan, split by experience level where the library makes that easy:
final = df[df["week"] == 12]
# Matplotlib: pass one array per box; a second grouping means positioning boxes yourself
fig, ax = plt.subplots(figsize=(7, 4))
ax.boxplot([final.loc[final["plan"] == p, "minutes"] for p in plans], tick_labels=plans)
ax.set(ylabel="Week 12 time (minutes)", title="Matplotlib")
plt.show()
# Seaborn: hue= splits each box by level
plt.figure(figsize=(7, 4))
ax = sns.boxplot(final, x="plan", y="minutes", hue="level")
ax.set(xlabel="", ylabel="Week 12 time (minutes)", title="Seaborn")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1)) # keep it off the boxes
plt.show()
# Plotly: color= splits the boxes, points="all" draws every runner next to them
fig = px.box(final, x="plan", y="minutes", color="level", points="all", title="Plotly",
labels={"plan": "", "minutes": "Week 12 time (minutes)"})
fig.show()

Matplotlib's box for each plan mixes beginners and experienced runners, so it's tall: the Intervals box covers both groups (medians of 25.9 and 23.2 minutes). Getting the split version means computing box positions and widths and building the legend by hand. Seaborn and Plotly both do it with one argument. Note the Matplotlib parameter name: labels= was renamed tick_labels= in Matplotlib 3.9, and 3.11 removed the old name, so older code now fails with TypeError: boxplot() got an unexpected keyword argument 'labels'. With Matplotlib 3.11, sns.boxplot also prints a vert: bool was deprecated warning; it comes from Seaborn 0.13.2's own code, and the Seaborn boxplot post shows how to silence it.
Which Should You Use: Matplotlib, Seaborn, or Plotly?
| Matplotlib | Seaborn | Plotly | |
|---|---|---|---|
| Best for | Full control, custom layouts, print and papers | Quick statistical charts and EDA | Interactive charts, dashboards, web pages |
| Input data | Arrays and lists (DataFrame columns work) | Long-format DataFrames | Long-format DataFrames (Plotly Express) |
| Statistics built in | None; compute them yourself | Means, CIs, KDE, regression, counts | Box, histogram, trendline="ols" (needs statsmodels) |
| Facets | plt.subplots() and a loop |
col=, row= on figure-level functions |
facet_col=, facet_row= |
| Interactivity | Zoom and pan in a desktop window or with the ipympl widget | Same as Matplotlib | Hover, zoom, legend toggling everywhere |
| Output | PNG, SVG, PDF, EPS | Same as Matplotlib | HTML; PNG, SVG, PDF through Kaleido |
| App support | st.pyplot in Streamlit, images elsewhere |
Same as Matplotlib | Native in Dash and st.plotly_chart |
| Large data | Fast for static plots up to millions of points | Bootstrapped CIs slow down on big data | Browser slows past ~100K points without WebGL |
A short way to decide:
- Exploring a dataset in a notebook: Seaborn, dropping to Matplotlib calls for tweaks.
- A figure for a paper, a report, or a slide with exact styling: Matplotlib, or Seaborn plus Matplotlib.
- Anything people will hover, zoom, or filter, or that goes in a Dash or Streamlit app: Plotly.
- You already have
df.plot()code: it's Matplotlib underneath, andpd.options.plotting.backend = "plotly"switches it to Plotly (see pandas with the Plotly backend).
Many projects use two: Seaborn or Matplotlib for analysis and static output, Plotly for what ends up on a web page.
Practical Tips
- Learn Matplotlib's
fig/axmodel even if you use Seaborn. Titles, axis limits, annotations, and saving a Seaborn chart are all Matplotlib calls. - Know Seaborn's two function levels. Axes-level functions (
sns.lineplot,sns.boxplot) draw on oneaxand acceptax=; figure-level ones (sns.relplot,sns.displot,sns.catplot) make their own figure and supportcol=/row=. - Speed up Seaborn on big data. Bootstrapping a CI for every point is slow;
errorbar="se"orerrorbar=Noneis much faster. - Check file sizes with Plotly.
fig.write_html()bundles about 4.8 MB of plotly.js (Plotly 7.2) unless you passinclude_plotlyjs="cdn". For more interactive libraries, see Python interactive charting libraries compared. - Match the house style.
sns.set_theme()restyles Seaborn and plain Matplotlib charts; Plotly usespio.templates.default(see Plotly templates and themes).
