Python Seaborn Grids

 # Seaborn — Grids

# Grid = multiple plots arranged automatically in rows and columns
# Instead of creating each plot manually, seaborn splits data by a category
# and draws one plot per group — all in one call
#
# Three grid types:
# FacetGrid → create any plot type, split by category
# PairGrid → one plot for every pair of columns (manual control)
# pairplot → shortcut for PairGrid with sensible defaults

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

# ── Sample data used throughout ───────────────────────────────────────────────
# 6 rows — 3 departments × 2 genders (1 male, 1 female per dept)
df = pd.DataFrame({
"dept": ["HR","HR","IT","IT","Finance","Finance"],
"gender": ["M", "F", "M", "F", "M", "F"],
"salary": [45000, 48000, 80000, 85000, 65000, 70000],
"score": [60, 65, 85, 88, 72, 75],
"age": [28, 30, 35, 38, 33, 36]
})

# ══════════════════════════════════════════════════════════════════════════════
# ── 1. FacetGrid — Draw any plot split by a category ─────────────────────────
# Step 1: Create the grid → FacetGrid(data, col= or row=)
# Step 2: Draw the plot → g.map(plot_function, "column_name")
#
# col= → one plot per unique value, arranged side by side
# row= → one plot per unique value, stacked top to bottom
# ══════════════════════════════════════════════════════════════════════════════

# ── col= — one plot per dept, side by side ────────────────────────────────────
g = sns.FacetGrid(df, col="dept") # split by dept → 3 columns
g.map(sns.histplot, "salary") # draw histplot of salary in each
plt.suptitle("Salary Distribution per Dept", y=1.02)
plt.show() # Output: 3 histograms side by side — one for HR, IT, Finance



No comments:

Post a Comment

Please comment below to feedback or ask questions.