Relationships, Matrix Charts And Styling in Seaborn
Relationships, Matrix Charts & Styling in Seaborn: Complete Guide
Variables ke beech relationships visualize karna, correlation heatmaps banana, pair-wise analysis karna, aur charts ko professional themes se polish karna — sab ek final guide mein.
📑 Is Guide Mein 3 Sections Cover Honge:
- Section A — Relationship Charts: scatterplot(), lineplot(), regplot(), lmplot(), relplot()
- Section B — Matrix & Advanced: heatmap(), clustermap(), pairplot(), jointplot(), FacetGrid
- Section C — Styling & Theming: set_theme(), set_style(), set_palette(), set_context(), despine()
Section A — Relationship & Regression Charts
1. sns.scatterplot() — Multi-Dimensional Scatter
🔍 Kya Hai: Seaborn scatterplot() matplotlib scatter() ka supercharged version hai — hue (color), size (bubble), aur style (marker shape) se ek scatter plot mein 5 dimensions tak dikhane ka power deta hai. DataFrame directly accept karta hai.
💻 Professional Multi-Dimensional Version:
fig, ax = plt.subplots(figsize=(12, 8))
sns.scatterplot(data=df, x="Experience", y="Salary",
hue="Department", # color = department
size="Rating", # dot size = rating (bubble chart!)
style="Gender", # marker shape = gender
sizes=(20, 200), # min/max dot size range
palette="Set2", # color palette
alpha=0.7, # transparency
edgecolor="#2c3e50", # dot border
linewidth=0.5, # border thickness
markers=["o", "s"], # circle for Male, square for Female
ax=ax
)
ax.set_title("Experience vs Salary (Color=Dept, Size=Rating, Shape=Gender)",
fontsize=14, fontweight="bold")
ax.set_xlabel("Experience (Years)", fontsize=12)
ax.set_ylabel("Salary (₹)", fontsize=12)
ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left", fontsize=9)
sns.despine()
plt.savefig("scatter_multi.png", dpi=150, bbox_inches="tight")
plt.show()
📋 scatterplot() Parameters:
| Parameter | Values | Description |
|---|---|---|
hue | column name | 3rd dimension — color mapping |
size | column name | 4th dimension — dot size mapping |
style | column name | 5th dimension — marker shape mapping |
sizes | (min, max) tuple | Dot size range |
2. sns.lineplot() — Line Chart with Confidence Band
🔍 Kya Hai: Seaborn lineplot() automatically confidence band (shaded area) dikhata hai jab multiple observations same x-value par hain. Yeh matplotlib plot() mein manually karna padta hai lekin Seaborn mein built-in hai — time-series trends ke liye perfect.
💻 Professional Version:
fig, ax = plt.subplots(figsize=(12, 6))
sns.lineplot(data=df, x="Experience", y="Salary",
hue="Department", # separate line per department
style="Gender", # line style per gender
palette="Set2",
linewidth=2.5,
markers=True, # show markers on data points
dashes=True, # different dash styles per style group
errorbar="ci", # "ci","sd","se","pi", None
estimator="mean", # aggregation function
sort=True, # sort x values
ax=ax
)
ax.set_title("Salary Trend by Experience (with CI Band)", fontsize=15, fontweight="bold")
ax.set_xlabel("Experience (Years)", fontsize=12)
ax.set_ylabel("Average Salary (₹)", fontsize=12)
ax.legend(bbox_to_anchor=(1.05, 1), fontsize=9)
sns.despine()
plt.savefig("lineplot_ci.png", dpi=150, bbox_inches="tight")
plt.show()
3. sns.regplot() — Scatter + Regression Line
🔍 Kya Hai: regplot() scatter plot ke saath automatically regression line aur confidence interval band fit karta hai. Linear, polynomial, aur logistic regression sab built-in hain — ek line mein statistical relationship visualize ho jaata hai.
💻 Linear + Polynomial Regression:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
# Linear Regression
sns.regplot(data=df, x="Experience", y="Salary",
scatter_kws={"alpha": 0.3, "s": 20, "color": "#3498db"},
line_kws={"color": "#e74c3c", "linewidth": 2.5},
ci=95, # confidence interval (95%)
order=1, # polynomial order (1=linear)
ax=ax1
)
ax1.set_title("Linear Regression (order=1)", fontsize=14, fontweight="bold")
# Polynomial Regression
sns.regplot(data=df, x="Experience", y="Salary",
scatter_kws={"alpha": 0.3, "s": 20, "color": "#2ecc71"},
line_kws={"color": "#e74c3c", "linewidth": 2.5},
ci=95,
order=2, # polynomial degree 2 (quadratic)
ax=ax2
)
ax2.set_title("Polynomial Regression (order=2)", fontsize=14, fontweight="bold")
for ax in [ax1, ax2]:
sns.despine(ax=ax)
plt.tight_layout()
plt.savefig("regplot.png", dpi=150, bbox_inches="tight")
plt.show()
📋 regplot() Parameters:
| Parameter | Values | Description |
|---|---|---|
order | 1, 2, 3 | Polynomial degree — 1=linear, 2=quadratic |
ci | 95, 99, None | Confidence interval band — None se hide |
logistic | True / False | Logistic regression (binary y) |
lowess | True / False | LOWESS smoothing (non-parametric) |
robust | True / False | Outlier-robust regression |
scatter_kws | dict | Dots styling — alpha, size, color |
line_kws | dict | Regression line styling |
4. sns.lmplot() — Faceted Regression (Figure-Level)
🔍 Kya Hai: lmplot() regplot() ka figure-level version hai — col/row se automatic faceted regression panels bante hain. Har department ya gender ke liye separate regression dikhana ho toh lmplot() ek line mein kar deta hai.
# Faceted regression — separate panel per department
g = sns.lmplot(data=df, x="Experience", y="Salary",
col="Department", # separate column per department
hue="Gender", # color by gender
col_wrap=2, # 2 panels per row
height=4, # panel height
aspect=1.3, # width ratio
palette=["#3498db", "#e74c3c"],
scatter_kws={"alpha": 0.4, "s": 15},
line_kws={"linewidth": 2},
ci=95,
order=1,
robust=False
)
g.fig.suptitle("Salary vs Experience — Per Department", fontsize=16, fontweight="bold", y=1.03)
plt.savefig("lmplot.png", dpi=150, bbox_inches="tight")
plt.show()
5. sns.relplot() — Figure-Level Relational (Scatter + Line)
🔍 Kya Hai: relplot() scatterplot() aur lineplot() dono ka figure-level version hai — kind="scatter" ya kind="line" se switch karo. col/row faceting built-in hai. Seaborn ka sabse versatile relational plotting function.
# Faceted scatter — Department panels + Gender color
g = sns.relplot(data=df, x="Experience", y="Salary",
kind="scatter", # "scatter" or "line"
col="Department",
hue="Gender",
size="Rating",
sizes=(20, 150),
col_wrap=2,
height=4,
aspect=1.3,
palette=["#3498db", "#e74c3c"],
alpha=0.6
)
g.fig.suptitle("Multi-Dimensional Relationship Analysis", fontsize=16, fontweight="bold", y=1.03)
plt.savefig("relplot.png", dpi=150, bbox_inches="tight")
plt.show()
Section B — Matrix & Advanced Charts
6. sns.heatmap() — Correlation & Matrix Visualization
🔍 Kya Hai: Seaborn heatmap() 2D numerical matrix ko color-coded grid mein visualize karta hai. Correlation matrix, confusion matrix, aur pivot table visualization — EDA ka sabse important single chart.
💻 Correlation Heatmap (Lower Triangle):
import numpy as np
corr = df.select_dtypes(include=["number"]).corr().round(2)
mask = np.triu(np.ones_like(corr, dtype=bool)) # upper triangle mask
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(corr,
mask=mask, # hide upper triangle (duplicate)
annot=True, # show values in cells
fmt=".2f", # number format
cmap="RdBu_r", # diverging colormap
center=0, # center value
vmin=-1, vmax=1, # value range
square=True, # square cells
linewidths=0.5, # cell border width
linecolor="white", # cell border color
cbar_kws={"shrink": 0.8, "label": "Correlation"},
annot_kws={"size": 11, "weight": "bold"},
ax=ax
)
ax.set_title("Feature Correlation Matrix", fontsize=16, fontweight="bold", pad=15)
plt.savefig("heatmap_corr.png", dpi=150, bbox_inches="tight")
plt.show()
7. sns.clustermap() — Hierarchical Clustered Heatmap
🔍 Kya Hai: clustermap() heatmap + hierarchical clustering combine karta hai — similar rows/columns ko automatically group karta hai aur dendrograms (tree diagrams) dikhata hai. Pattern discovery ke liye heatmap se better.
corr = df.select_dtypes(include=["number"]).corr()
g = sns.clustermap(corr,
annot=True, # show values
fmt=".2f",
cmap="coolwarm", # colormap
center=0,
linewidths=0.5,
figsize=(10, 8), # figure size
method="ward", # clustering method: "ward","complete","average","single"
metric="euclidean", # distance metric
standard_scale=1, # 0=row, 1=column standardization
dendrogram_ratio=0.15, # dendrogram size
cbar_pos=(0.02, 0.8, 0.03, 0.15),
tree_kws={"linewidths": 1.5}
)
g.fig.suptitle("Clustered Correlation Map", fontsize=16, fontweight="bold", y=1.02)
plt.savefig("clustermap.png", dpi=150, bbox_inches="tight")
plt.show()
8. sns.pairplot() — All-Pairs Scatter Matrix
🔍 Kya Hai: pairplot() har numerical column ka har doosre column ke saath scatter plot banata hai — diagonal par distribution. Ek call mein complete pairwise relationship matrix ban jaati hai. EDA ka most powerful single function.
g = sns.pairplot(df[["Salary", "Experience", "Age", "Rating", "Department"]],
hue="Department", # color by department
palette="Set2",
diag_kind="kde", # diagonal: "hist","kde",None
kind="scatter", # off-diagonal: "scatter","kde","hist","reg"
plot_kws={"alpha": 0.5, "s": 15},
diag_kws={"alpha": 0.6, "linewidth": 2},
height=2.5, # each panel size
aspect=1,
corner=True # lower triangle only (cleaner)
)
g.fig.suptitle("Pairwise Relationship Matrix", fontsize=16, fontweight="bold", y=1.02)
plt.savefig("pairplot.png", dpi=150, bbox_inches="tight")
plt.show()
📋 pairplot() Parameters:
| Parameter | Values | Description |
|---|---|---|
diag_kind | "hist","kde",None | Diagonal panels ka chart type |
kind | "scatter","kde","hist","reg" | Off-diagonal chart type |
corner | True / False | Sirf lower triangle dikhana |
vars | list of columns | Specific columns select karna |
9. sns.jointplot() — Bivariate + Marginal Distributions
🔍 Kya Hai: jointplot() center mein scatter/KDE dikhata hai aur margins (edges) par individual distributions — ek chart mein 3 views: relationship + x distribution + y distribution. Bivariate analysis ka complete picture.
# Scatter + Marginal Histograms
g = sns.jointplot(data=df, x="Experience", y="Salary",
kind="scatter", # "scatter","kde","hist","hex","reg","resid"
hue="Gender",
palette=["#3498db", "#e74c3c"],
height=8, # figure size
ratio=5, # center vs margin size ratio
space=0.2, # gap between center and margins
marginal_kws={"bins": 20, "alpha": 0.6},
joint_kws={"alpha": 0.5, "s": 20}
)
g.fig.suptitle("Experience vs Salary — Joint Distribution", fontsize=15, fontweight="bold", y=1.02)
plt.savefig("jointplot.png", dpi=150, bbox_inches="tight")
plt.show()
# KDE Version — density contours
g = sns.jointplot(data=df, x="Experience", y="Salary",
kind="kde", fill=True, cmap="YlOrRd", levels=15, height=8)
plt.savefig("jointplot_kde.png", dpi=150, bbox_inches="tight")
plt.show()
# Hex Version — large data density
g = sns.jointplot(data=df, x="Experience", y="Salary",
kind="hex", cmap="Blues", height=8)
plt.savefig("jointplot_hex.png", dpi=150, bbox_inches="tight")
plt.show()
10. sns.FacetGrid() — Custom Multi-Panel Charts
🔍 Kya Hai: FacetGrid sabse flexible multi-panel tool hai — koi bhi plotting function (matplotlib ya seaborn) ko faceted grid mein map kar sakte hain. displot, catplot, relplot sab internally FacetGrid use karte hain.
# Custom FacetGrid — any function mapped
g = sns.FacetGrid(df,
col="Department", # columns
row="Gender", # rows
hue="Gender", # color
height=3.5,
aspect=1.2,
palette=["#3498db", "#e74c3c"],
margin_titles=True # show row/col titles on margins
)
# Map any plotting function
g.map_dataframe(sns.histplot, x="Salary", kde=True, bins=15, alpha=0.6)
# Add reference lines to all panels
g.map(lambda **kwargs: plt.axvline(df["Salary"].mean(), color="red", linestyle="--", alpha=0.5))
g.fig.suptitle("Salary Distribution — Department × Gender Grid", fontsize=16, fontweight="bold", y=1.03)
g.add_legend()
plt.savefig("facetgrid.png", dpi=150, bbox_inches="tight")
plt.show()
Section C — Styling & Theming
11. sns.set_theme() — Global Theme Configuration
# ===== set_theme() — All-in-one global configuration =====
sns.set_theme(
style="whitegrid", # background style
context="notebook", # sizing context
palette="Set2", # default colors
font="Arial", # font family
font_scale=1.1, # font size multiplier
rc={ # custom rcParams
"figure.figsize": (10, 6),
"axes.titleweight": "bold",
"axes.labelweight": "bold"
}
)
12. sns.set_style() — Background Styles
# ===== 5 BUILT-IN STYLES =====
sns.set_style("whitegrid") # ✅ White bg + grid (MOST POPULAR)
sns.set_style("darkgrid") # Gray bg + grid (seaborn default)
sns.set_style("white") # Clean white — minimal
sns.set_style("dark") # Dark bg — no grid
sns.set_style("ticks") # White bg + tick marks (scientific)
# Custom overrides
sns.set_style("whitegrid", {
"grid.linestyle": "--",
"grid.alpha": 0.3,
"axes.edgecolor": "#cccccc"
})
# Temporary style
with sns.axes_style("dark"):
fig, ax = plt.subplots()
sns.histplot(data=df, x="Salary", ax=ax)
plt.show()
# Original style restored automatically!
13. sns.set_palette() & color_palette() — Color Systems
# ===== BUILT-IN PALETTES =====
# Qualitative (distinct categories)
sns.set_palette("Set1") # bold, distinct
sns.set_palette("Set2") # pastel, professional ✅
sns.set_palette("Set3") # light pastel
sns.set_palette("Pastel1") # very light
sns.set_palette("tab10") # matplotlib default 10 colors
# Sequential (gradient)
sns.set_palette("Blues") # light to dark blue
sns.set_palette("YlOrRd") # yellow to red (heatmaps)
# Diverging
sns.set_palette("RdBu") # red to blue (correlations)
sns.set_palette("coolwarm") # cool blue to warm red
# ===== CUSTOM PALETTE =====
my_colors = ["#3498db", "#2ecc71", "#e74c3c", "#f39c12", "#9b59b6"]
sns.set_palette(my_colors)
# Generate palette programmatically
pal = sns.color_palette("husl", 8) # 8 evenly spaced hues
pal = sns.color_palette("light:#3498db", 6) # light to dark blue gradient
pal = sns.color_palette("blend:#3498db,#e74c3c", 5) # blue to red blend
# Preview palette
sns.palplot(sns.color_palette("Set2"))
plt.title("Set2 Palette")
plt.savefig("palette_preview.png", dpi=150, bbox_inches="tight")
plt.show()
14. sns.set_context() — Output Size Presets
# ===== 4 CONTEXT PRESETS =====
sns.set_context("paper") # smallest — research papers
sns.set_context("notebook") # medium — Jupyter notebooks ✅ (default)
sns.set_context("talk") # large — presentations/slides
sns.set_context("poster") # largest — posters/billboards
# Custom font scale
sns.set_context("notebook", font_scale=1.3)
# Custom overrides
sns.set_context("talk", rc={
"lines.linewidth": 3,
"axes.titlesize": 18
})
15. sns.despine() — Clean Spine Removal
# ===== DESPINE OPTIONS =====
# Default — remove top & right spines
sns.despine()
# Custom — choose which to remove
sns.despine(
top=True, # remove top spine
right=True, # remove right spine
left=False, # keep left spine
bottom=False, # keep bottom spine
offset=10, # move spines away from data (pixels)
trim=True # trim spines to data range
)
# Specific axes
fig, (ax1, ax2) = plt.subplots(1, 2)
sns.despine(ax=ax1) # only despine ax1
sns.despine(ax=ax2, left=True) # remove left spine too from ax2
⭐ Recommended Professional Setup Template
# ===== COPY-PASTE THIS AT TOP OF EVERY NOTEBOOK =====
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Professional theme setup
sns.set_theme(
style="whitegrid",
context="notebook",
palette="Set2",
font_scale=1.1,
rc={
"figure.figsize": (10, 6),
"figure.dpi": 100,
"savefig.dpi": 150,
"axes.titleweight": "bold",
"axes.labelweight": "bold",
"axes.titlesize": 14,
"axes.labelsize": 12,
"axes.spines.top": False,
"axes.spines.right": False
}
)
print("✅ Professional visualization setup loaded!")
Master Reference: Complete Seaborn Function Guide
| Category | Function | Purpose | Level |
|---|---|---|---|
| Distribution | histplot() | Histogram + KDE | Axes |
kdeplot() | Smooth density curve | Axes | |
displot() | Faceted distribution | Figure | |
| Categorical | barplot() | Mean + CI bars | Axes |
boxplot() | Spread + outliers | Axes | |
violinplot() | Distribution shape | Axes | |
catplot() | All categorical faceted | Figure | |
| Relational | scatterplot() | Multi-dim scatter | Axes |
regplot() | Scatter + regression | Axes | |
relplot() | Faceted relational | Figure | |
| Matrix | heatmap() | Color-coded matrix | Axes |
pairplot() | All-pairs matrix | Figure | |
jointplot() | Bivariate + marginals | Figure |
🎉 Seaborn Masterclass Complete!
Congratulations! Aapne 3 comprehensive parts mein 15 Seaborn functions cover kiye hain — Distribution se Matrix Charts tak, Styling se Professional Templates tak. Ab aap publication-quality statistical visualizations confidently create kar sakte hain.
Happy Visualizing! 📊🚀
💬 Comments (0)
Loading comments...