Seaborn Master Hub + Recipes (Python)
Figure‑level vs axis‑level APIs, chart recipes, facets, palettes, themes, statistical annotations, and troubleshooting—copy‑paste ready.
Quickstart: Setup & Style
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(context="notebook", style="whitegrid", palette="deep")
# Alternatives: style=("white","dark","ticks"), context=("paper","talk","poster")
Figure‑Level API
relplot (scatter/line)
import seaborn as sns
df = sns.load_dataset("tips")
g = sns.relplot(data=df, x="total_bill", y="tip", hue="sex", col="time", kind="scatter")
g.set_titles("{col_name}"); g.set_axis_labels("Bill ($)", "Tip ($)")
plt.show()
catplot (categorical)
g = sns.catplot(data=df, x="day", y="tip", hue="sex", kind="violin", split=True, inner="quartile")
g.despine(left=True); plt.show()
displot (distributions)
g = sns.displot(data=df, x="total_bill", hue="time", kind="kde", fill=True, height=4, aspect=1.4)
plt.show()
lmplot (regression)
g = sns.lmplot(data=df, x="total_bill", y="tip", hue="smoker", height=4, aspect=1.3)
plt.show()
Axis‑Level API
Line/Scatter/Bar
fig, ax = plt.subplots(figsize=(6,4))
sns.lineplot(data=df, x="size", y="total_bill", hue="time", marker="o", ax=ax)
ax.set(title="Bill vs Size", xlabel="Party size", ylabel="Bill ($)")
sns.despine()
plt.tight_layout(); plt.show()
Histogram/ KDE
fig, ax = plt.subplots()
sns.histplot(data=df, x="total_bill", hue="sex", multiple="stack", bins=30, ax=ax)
plt.show()
Box/Violin/Strip
fig, ax = plt.subplots()
sns.boxplot(data=df, x="day", y="tip", hue="smoker", ax=ax)
sns.stripplot(data=df, x="day", y="tip", hue="smoker", dodge=True, size=2, color="k", alpha=.5, ax=ax)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2], title="Smoker")
plt.show()
Count/Point/Bar (ci)
fig, ax = plt.subplots()
sns.pointplot(data=df, x="day", y="tip", hue="sex", errorbar="se", dodge=True, ax=ax)
plt.show()
Pairplot & Jointplot
iris = sns.load_dataset("iris")
# Pairplot
g = sns.pairplot(data=iris, hue="species", corner=True, diag_kind="kde")
g.fig.suptitle("Iris Pairwise", y=1.02); plt.show()
# Jointplot
g = sns.jointplot(data=iris, x="sepal_length", y="sepal_width", hue="species", kind="kde", fill=True)
plt.show()
Heatmaps & Correlations
import numpy as np
num = iris.select_dtypes(np.number)
corr = num.corr()
plt.figure(figsize=(7,5))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", vmin=-1, vmax=1, linewidths=.5, square=True)
plt.title("Correlation Matrix"); plt.tight_layout(); plt.show()
# Clustered heatmap
sns.clustermap(corr, cmap="vlag", center=0, figsize=(7,7), dendrogram_ratio=.1)
plt.show()
Palettes & Themes
# Built‑ins: "deep","muted","pastel","bright","dark","colorblind"
sns.set_palette("colorblind")
# Continuous: cubehelix_palette, light_palette, dark_palette, diverging_palette
pal = sns.cubehelix_palette(start=.5, rot=-.75, gamma=.8, as_cmap=True)
sns.kdeplot(data=df, x="total_bill", fill=True, cmap=pal)
plt.show()
# Context & style
sns.set_theme(context="talk", style="ticks", rc={"axes.spines.right": False, "axes.spines.top": False})
FacetGrid & Small Multiples
g = sns.FacetGrid(df, col="day", row="time", margin_titles=True, height=3)
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip", hue="sex", alpha=.8)
g.add_legend(); g.set_axis_labels("Bill ($)","Tip ($)")
for ax in g.axes.flat: ax.tick_params(axis="x", rotation=30)
plt.show()
Statistical Annotations
# Example: add mean/CI text
import numpy as np
fig, ax = plt.subplots()
sns.barplot(data=df, x="day", y="tip", errorbar="ci", ax=ax)
grouped = df.groupby("day")["tip"].agg(["mean","count","std"])
for i,(day,row) in enumerate(grouped.iterrows()):
ax.text(i, row["mean"] + 0.2, f"{row['mean']:.2f}", ha="center", va="bottom", fontsize=9)
plt.show()
# Trendline with confidence region (regplot)
fig, ax = plt.subplots()
sns.regplot(data=df, x="total_bill", y="tip", scatter_kws={"alpha":.5, "s":20}, line_kws={"color":"crimson"}, ax=ax)
plt.show()
Export (SVG/PNG)
fig = g.figure if "g" in locals() else plt.gcf()
fig.savefig("figure.svg", bbox_inches="tight")
fig.savefig("figure.png", dpi=200, bbox_inches="tight")
Performance Tips
- Downsample large datasets; limit markers for scatter and use alpha to reduce overplotting.
- Use axis‑level functions within a pre‑created figure/axes to avoid repeated figure creation.
- Cache aggregated summaries (groupby, pivots) before plotting to minimize repeated computation.
- For extremely large data, pre‑bin densities (hexbin via Matplotlib) and plot the aggregate.
# Example: binning before plot
import pandas as pd, numpy as np
data = pd.DataFrame({"x":np.random.randn(200_000), "y":np.random.randn(200_000)})
bins = pd.cut(data["x"], bins=60)
agg = data.groupby(bins)["y"].mean().reset_index()
sns.lineplot(data=agg, x="x", y="y") # convert interval to midpoint for x if needed
Troubleshooting & FAQ
Legends duplicated/overlapping
Manually control legend handles/labels from ax.get_legend_handles_labels(); place with bbox_to_anchor.
Different hues across facets
Set a fixed palette and hue_order globally to keep consistent colors across multiple plots.
Wide DataFrame not accepted
Most Seaborn APIs prefer tidy/long data. Use pandas.melt or specify wide‑form functions intentionally.
Slow pairplot/jointplot
Subset columns, sample rows, or use corner=True. For jointplot, switch kind to hex or hist for speed.
Matplotlib and Seaborn style conflicts
Call sns.set_theme at the start; avoid resetting rcParams mid‑session unless necessary.
Axis labels overlap
Rotate ticks, use tight_layout(), or adjust figure size/aspect ratio.
FAQ
Figure‑level vs axis‑level? Figure‑level functions create their own figure/grid and are ideal for faceting; axis‑level draw onto a provided Matplotlib axes for maximum control.
How to keep color mapping consistent across plots? Define a palette and a fixed hue_order. Use the same order and palette wherever the categorical variable appears.
How to add statistical test results? Compute with SciPy/Statsmodels and annotate using ax.text/lines; or use community helpers that render p‑values on plots.
© 2025 Pythoneo · Designed to be highly linkable: comprehensive, evergreen, copy‑paste friendly, with styling, facets, and troubleshooting built‑in.