Python · Statistical Visualization · Seaborn

Seaborn
Cheatsheet

A quick reference guide for statistical data visualization using Seaborn in Python — covering relational plots, distributions, categorical plots, heatmaps, and themes.

Library: seaborn ≥ 0.12
Language: Python 3
Level: Beginner → Intermediate
Topics: 10 sections
📖 View Official Docs 🖼️ Examples Gallery

📦 1. Importing & Setup

Seaborn builds on top of Matplotlib — import both. Always pass a DataFrame directly to Seaborn functions.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Check version
print(sns.__version__)

# Set default theme at start
sns.set_theme(style="darkgrid")  # or whitegrid, dark, white, ticks
sns.set_context("notebook")     # paper, notebook, talk, poster

🗂️ 2. Built-in Datasets

Seaborn includes several ready-to-use datasets — great for quick experiments.

# List all available datasets
sns.get_dataset_names()

# Load a dataset
tips    = sns.load_dataset("tips")       # restaurant tips
iris    = sns.load_dataset("iris")       # flower measurements
titanic = sns.load_dataset("titanic")   # passenger survival
flights = sns.load_dataset("flights")   # monthly passengers
penguins= sns.load_dataset("penguins")  # penguin measurements
fmri    = sns.load_dataset("fmri")      # brain signals

🔵 3. Relational Plot (Scatter)

sns.relplot() and sns.scatterplot() are the go-to for exploring relationships between numeric variables.

tips = sns.load_dataset("tips")

# Figure-level relplot
sns.relplot(data=tips, x="total_bill", y="tip",
           hue="smoker", size="size", style="time")

# Axes-level scatterplot
sns.scatterplot(data=tips, x="total_bill", y="tip",
               hue="day", palette="Set2")
plt.show()

📈 4. Line Plot

fmri = sns.load_dataset("fmri")

# Figure-level line plot
sns.relplot(data=fmri, x="timepoint", y="signal",
           kind="line", hue="event", style="region",
           col="region")          # facet by region

# Axes-level
sns.lineplot(data=fmri, x="timepoint", y="signal",
            hue="event", errorbar="sd")  # show std dev band
plt.show()

📉 5. Distribution Plots

Histogram + KDE

penguins = sns.load_dataset("penguins")

# histplot
sns.histplot(data=penguins,
            x="flipper_length_mm",
            hue="species", kde=True)

# kdeplot only
sns.kdeplot(data=penguins,
           x="body_mass_g",
           hue="species", fill=True)

ECDF & displot

# Empirical CDF
sns.ecdfplot(data=penguins,
            x="body_mass_g",
            hue="species")

# Figure-level displot
sns.displot(data=penguins,
           x="flipper_length_mm",
           col="species", kde=True)

📊 6. Categorical Plots

tips = sns.load_dataset("tips")

# Box plot
sns.boxplot(data=tips, x="day", y="total_bill", hue="smoker")

# Violin plot (distribution + box)
sns.violinplot(data=tips, x="day", y="total_bill", hue="sex",
              split=True)

# Bar plot (mean + confidence interval)
sns.barplot(data=tips, x="day", y="total_bill", hue="sex")

# Strip plot (raw data points)
sns.stripplot(data=tips, x="day", y="tip", jitter=True)

# Count plot
sns.countplot(data=tips, x="day", hue="sex")

plt.show()

🔲 7. Pairplot

Quickly visualize pairwise relationships across all numeric columns in a DataFrame.

iris = sns.load_dataset("iris")

# Basic pairplot
sns.pairplot(iris)

# With hue (colour by class)
sns.pairplot(iris, hue="species")

# Diagonal: KDE instead of histogram
sns.pairplot(iris, hue="species", diag_kind="kde")

# Select specific columns
sns.pairplot(iris,
            vars=["sepal_length", "petal_length"],
            hue="species")
plt.show()

🌡️ 8. Heatmap

Ideal for displaying correlation matrices and pivot tables.

flights = sns.load_dataset("flights")
pivot   = flights.pivot_table(index="month", columns="year",
                               values="passengers")

# Basic heatmap
sns.heatmap(pivot, cmap="YlGnBu")

# With annotations
sns.heatmap(pivot, annot=True, fmt="d", linewidths=0.5)

# Correlation matrix
corr = iris.drop("species", axis=1).corr()
sns.heatmap(corr, annot=True, cmap="coolwarm",
           vmin=-1, vmax=1, center=0)
plt.show()

🎨 9. Styling & Themes

Themes & Contexts

# Themes (background style)
sns.set_style("darkgrid")   # default
sns.set_style("whitegrid")
sns.set_style("dark")
sns.set_style("white")
sns.set_style("ticks")

# Context (font/element size)
sns.set_context("paper")
sns.set_context("notebook")  # default
sns.set_context("talk")
sns.set_context("poster")

Palettes & Colors

# Named palettes
sns.set_palette("Set2")
sns.set_palette("husl")
sns.set_palette("muted")
sns.set_palette("deep")

# Preview a palette
sns.color_palette("Set2")
sns.palplot(sns.color_palette("Set2"))

# Reset to defaults
sns.reset_defaults()

🖼️ 10. Figure Customization

Seaborn figure-level functions return a FacetGrid; axes-level functions return an Axes object. Use Matplotlib calls to customize further.

# Axes-level: customize with matplotlib
ax = sns.scatterplot(data=tips, x="total_bill", y="tip")
ax.set_title("Tips vs Total Bill", fontsize=14)
ax.set_xlabel("Total Bill ($)")
ax.set_ylabel("Tip ($)")
plt.tight_layout()

# Figure-level: use FacetGrid methods
g = sns.relplot(data=tips, x="total_bill", y="tip",
               col="time", hue="smoker")
g.set_axis_labels("Bill ($)", "Tip ($)")
g.set_titles(col_template="{col_name} service")
g._legend.set_title("Smoker?")

# Saving
plt.savefig("seaborn_plot.png", dpi=300, bbox_inches="tight")

✅ Best Practices

📊 Choose the Right Plot

Use scatter/line for relationships, box/violin for distributions, bar for comparisons, heatmap for matrices.

🎨 Use Color Meaningfully

Map hue to a meaningful variable. Use sequential palettes for ordered data and qualitative for categories.

🧹 Keep Visuals Simple

Avoid overloading hue + size + style simultaneously. Each encoding should tell a distinct story.

🏷️ Label Clearly

Always set axis labels and a title. Use set_axis_labels() on FacetGrids.

📐 Tidy Data First

Seaborn works best with long-format (tidy) DataFrames. Use pd.melt() to reshape if needed.

💾 Save Before Show

Always call plt.savefig() before plt.show() — showing clears the figure buffer.

📚 Further Learning