import seaborn as sns★The one import you always write.import matplotlib.pyplot as pltStill needed forshow,savefig, fine-tuning.import seaborn.objects as soThe newer declarative "objects" interface (card 12).sns.set_theme()★Apply seaborn's look — call once, up top.sns.set_theme(style="whitegrid", context="talk", palette="deep")★Look · sizing · colors in one call.sns.set_style("darkgrid")darkgrid·whitegrid·dark·white·ticks(defaultdarkgrid).sns.set_context("notebook")Scale text/lines:paper·notebook·talk·poster.sns.despine()Remove the top & right spines for a cleaner frame.tips = sns.load_dataset("tips")★Built-in demo DataFrames:penguins,iris,titanic…
data=df★Pass a tidy / long-form DataFrame; refer to columns by name.x="total_bill", y="tip"★Map columns to the axes by string name.hue="sex"★Color by a variable — auto legend. The workhorse channel.size="size"Scale point/line size by a variable.style="smoker"Vary marker shape / dash pattern by a variable.col="time", row="day"★Split into a grid of panels (facets) — figure-level only.sns.scatterplot(data=df, x="a", y="b", hue="c")The shape every seaborn function takes.
sns.relplot(data=df, x=a, y=b)★fig-levelDefaultkind="scatter".sns.relplot(…, kind="line")★Line plot; auto-aggregates & draws a CI band.sns.scatterplot(data=df, x=a, y=b)axes-levelDraws on the current Axes; returns it.sns.lineplot(data=df, x=a, y=b)★Averages repeatedxand shades the CI.sns.relplot(…, hue=c, size=n, style=c)Layer several semantic channels at once.sns.relplot(…, col=c, row=c)Facet into a panel grid.sns.lineplot(…, errorbar="sd")CI band by default; use"sd",None,("pi",95).
sns.displot(data=df, x=a)★fig-levelDefaultkind="hist".sns.histplot(data=df, x=a, bins=30)★Histogram;binwidth=also works.sns.histplot(…, kde=True)★Overlay a smooth density curve on the bars.sns.kdeplot(data=df, x=a, fill=True)★Smooth density estimate (usefill, notshade).sns.ecdfplot(data=df, x=a)Empirical cumulative distribution — no binning choice.sns.rugplot(data=df, x=a)Little ticks for each raw observation.sns.displot(…, multiple="stack")Withhue:layer·stack·dodge·fill.sns.histplot(data=df, x=a, y=b)Givexandy→ a 2-D (bivariate) histogram.
sns.catplot(data=df, x=cat, y=num)★fig-levelDefaultkind="strip"; the gateway to all categorical kinds.sns.stripplot(data=df, x=cat, y=num)Jittered points, one strip per category.sns.swarmplot(data=df, x=cat, y=num)Non-overlapping "beeswarm" — best for small n.sns.catplot(…, kind="swarm")Same drawer, reached via the dispatcher.sns.stripplot(…, hue=c, dodge=True)Split each category byhueside-by-side.
sns.boxplot(data=df, x=cat, y=num)★Quartiles + whiskers + outliers.sns.violinplot(data=df, x=cat, y=num)★Box + a mirrored KDE density shape.sns.violinplot(…, hue=c, split=True)Half-violin perhuelevel — compact comparison.sns.boxenplot(data=df, x=cat, y=num)"Letter-value" box — shows tails better for large n.sns.catplot(…, kind="box")Any of these viakind=for free faceting.
sns.barplot(data=df, x=cat, y=num)★Bar of the mean (default) + CI — not a raw count.sns.countplot(data=df, x=cat)★Bar of row counts per category (a histogram of a category).sns.pointplot(data=df, x=cat, y=num)Point estimate + CI, joined — good for interactions.sns.barplot(…, estimator="median", errorbar="ci")Swap the summary statistic and the error bar.sns.barplot(…, hue=c)Grouped ("dodged") bars automatically.
sns.lmplot(data=df, x=a, y=b)★fig-levelScatter + linear fit + CI, with faceting.sns.regplot(data=df, x=a, y=b)axes-levelSame fit on one Axes; composes into subplots.sns.lmplot(…, hue=c, col=c)A separate fit per group / per panel.sns.regplot(…, order=2)Polynomial fit of the given degree.sns.regplot(…, lowess=True)Non-parametric locally-weighted smoother.sns.regplot(…, logistic=True)Logistic fit for a 0/1 outcome.sns.residplot(data=df, x=a, y=b)Plot residuals to check whether a fit is appropriate.
sns.heatmap(df.corr())★Render a 2-D matrix as a grid of colored cells.sns.heatmap(m, annot=True, fmt=".2f")★Write each value inside its cell.sns.heatmap(m, cmap="vlag", center=0)Diverging colormap centered on zero (great for corr).sns.clustermap(m)Heatmap + hierarchical-clustering dendrograms, reordered.sns.heatmap(m, linewidths=.5, cbar=False)Cell borders; hide the color bar.m = df.pivot(index=r, columns=c, values=v)Reshape long → wide first; heatmap needs a matrix.
sns.pairplot(df, hue=c)★Every pairwise scatter + per-variable diagonals.sns.jointplot(data=df, x=a, y=b, kind="hex")★Bivariate plot with marginal distributions.sns.jointplot(…, kind="reg")scatter·kde·hex·reg·hist.g = sns.FacetGrid(df, col=c, row=c)Build an empty panel grid to draw onto.g.map_dataframe(sns.histplot, "x")Draw the same plot into every panel.sns.PairGrid(df).map_offdiag(sns.scatterplot)Full control: different plot on diagonal vs off-diagonal.g.add_legend(); g.set_axis_labels("x", "y")Grid finishing touches.
sns.color_palette("deep")★Qualitative:deep·muted·pastel·bright·dark·colorblind.sns.color_palette("husl", 8)Evenly-spaced distinct hues for n categories.sns.color_palette("crest", as_cmap=True)Sequential (crest·flare·rocket·mako) for ordered data.sns.color_palette("vlag")Diverging (vlag·icefire) for data centered on a midpoint.sns.scatterplot(…, hue=c, palette="Set2")Any named palette, inline on the call.sns.set_palette("pastel")Set the default color cycle globally.palette= without hue= → ignorednoteA palette needs ahueassignment to have anything to color.
so.Plot(df, x="a", y="b")★The declarative base object — a grammar of graphics..add(so.Dot())★A layer's Mark:Dot·Line·Bar·Area·Band·Text..add(so.Bar(), so.Agg())★Mark + Stat:Agg·Est·Hist·KDE·Count·PolyFit..add(so.Dot(), so.Dodge(), so.Jitter())Move: reposition —Dodge·Jitter·Stack·Shift..facet("c").pair(x=[…])Small multiples & variable pairings, built in..scale(color="viridis")Control how each data channel maps to a visual property..label(…).limit(…).theme(…)Declarative finishing methods, chainable..layout(size=(7,5)).save("f.svg")Size, then.save()/.show()/.on(ax)to embed.
ax = sns.boxplot(…)★Axes-level returns a matplotlib Axes — use any of its methods.ax.set(title="…", xlabel="…", ylim=(0,5))★Batch matplotlib tweaks in one call.g = sns.relplot(…)Figure-level returns a gridg(FacetGrid) — style viag.g.set_axis_labels("x", "y")Seaborn's own label setter for the whole grid.g.set_titles("{col_name}")Template each panel's title from the facet value.g.figure / g.axesReach the underlying matplotlib Figure / Axes array.sns.relplot(…, height=4, aspect=1.5)★Size figure-level plots withheight×aspect, notfigsize.
plt.show()★Render — automatic in notebooks, explicit in scripts.plt.savefig("fig.png", dpi=300, bbox_inches="tight")★Export an axes-level plot;tighttrims whitespace.g.savefig("fig.png", dpi=300)Save a figure-level grid (call ong, notplt).plot.save("fig.svg", bbox_inches="tight")Objects-interface export.# save BEFORE showorderSome backends clear the figure onshow(). Use.svgfor vectors.
scatterplot · histplot · boxplot · kdeplot · regplot★axes-levelDrop-in for matplotlib; draws on the current Axes viagca().returns a matplotlib Axes · accepts ax=★Compose it into your ownplt.subplots()figure.relplot · displot · catplot · lmplot★fig-levelOne dispatcher per module; each builds its own figure.returns a FacetGrid · ignores ax=★Legend sits outside;col=/row=faceting for free.kind="…" picks the axes-level drawerdisplot(kind="kde")≡kdeplot().explore → figure-level · compose → axes-level★The practical rule of thumb.
sns.relplot(…, ax=ax)no-opFigure-level ignoresax=→ you get an extra blank figure.plt.subplots(); sns.displot(…)blankA figure-level call after making axes leaves the axes empty.boxplot(x=numeric)indexedCategorical plots force a 0-indexed category axis — even for numbers.palette= with no hue=Does nothing — there's no variable to map colors to.sns.set_theme()Rewrites global matplotlibrcParams— affects all later plots.figsize= on figure-levelUseheight&aspectinstead;figsizeis ignored.shade=Trueremovedkdeplot(shade=)is gone — usefill=True.