পাঠ ১৮ · ২৫-এর মধ্যে · মডিউল ২

Seaborn — সুন্দর ডেটা ভিজ্যুয়াল

Seaborn statistical plots
৭ মিনিট পড়া শুরু · Beginner ব্রাউজারে কোড চালান

এই পাঠে যা শিখবেন

  • Seaborn কী — Matplotlib-এর উপর কেন আরেকটি স্তর
  • Theme, palette, context — সুন্দর default
  • scatterplot, regplot — সম্পর্ক ও regression
  • histplot, kdeplot — distribution
  • boxplot, violinplot — categorical-এ distribution
  • heatmap — correlation matrix
  • pairplot, catplot, relplot — multi-panel facet
  • Iris dataset দিয়ে complete EDA mini

১ · Seaborn কী?

SeabornSeabornMatplotlib-এর উপর তৈরি high-level Python visualization library — Michael Waskom (২০১২)। Statistical plot, DataFrame-native API, সুন্দর default — EDA-র জন্য standard tool। হলো Matplotlib-এর উপর তৈরি একটি high-level statistical visualization library। Matplotlib দিয়ে যে কাজ ১৫-২০ লাইনে — Seaborn-এ সেটা ২-৩ লাইনে। এর সবচেয়ে বড় শক্তি — DataFrame-এর column-name দিয়ে সরাসরি plot, statistical estimation built-in (regression, KDE, CI), এবং সুন্দর default styling।

Seaborn-এর তিন স্তম্ভ

১) Statistical defaults: regression line, kernel density, confidence interval — auto।
২) DataFrame-native: x="col1", y="col2", hue="class" — column-name দিয়ে কাজ।
৩) Beautiful out of the box: theme, palette — কোনো configuration ছাড়াই presentation-ready।

Matplotlib = কাঁচামাল (চাল, ডাল, মশলা — সব নিজে রান্না করতে হবে)। Seaborn = প্রস্তুত খাবার (চটপট পরিবেশন করুন, স্বাদ বেশ ভালো)। দু'টোরই জায়গা আছে — Seaborn দ্রুত EDA-র জন্য, matplotlib custom presentation-এর জন্য।

২ · Theme ও global setup

sns.set_theme() এক লাইনে — ছবির গ্রিড, font, color palette, context — সব সুন্দর হয়ে যায়। context paper/notebook/talk/poster — যেখানে দেখাবেন সেখানের জন্য element size adjust।

Python · Seaborn
import seaborn as sns
import matplotlib.pyplot as plt

# Global theme — এক লাইনে presentation-ready
sns.set_theme(style="whitegrid", palette="deep", context="notebook")

# Built-in dataset লোড
iris = sns.load_dataset("iris")
print(iris.head())
print(iris.shape, iris["species"].unique())

    
sns.load_dataset() — github থেকে famous datasets টানে: iris, titanic, tips, penguins, flights। Practice ও demo-এর জন্য আদর্শ।

৩ · scatterplot ও regplot — সম্পর্ক

দু'টি continuous variable-এর সম্পর্ক দেখার সবচেয়ে সরল উপায় — scatter plot। hue parameter দিয়ে তৃতীয় (categorical) variable color দিয়ে এনকোড। regplot automatic regression line + confidence interval এঁকে দেয়।

Python · scatter + reg
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid")
iris = sns.load_dataset("iris")

# (১) hue দিয়ে scatter — তিন species আলাদা রঙে
fig, axes = plt.subplots(1, 2, figsize=(12, 4))

sns.scatterplot(
    data=iris,
    x="sepal_length", y="petal_length",
    hue="species", style="species", s=70,
    ax=axes[0]
)
axes[0].set_title("Iris — sepal vs petal (hue=species)")

# (২) regplot — automatic regression line + 95% CI
sns.regplot(
    data=iris, x="sepal_length", y="petal_length",
    scatter_kws={"alpha": 0.5}, ax=axes[1]
)
axes[1].set_title("Linear fit + confidence band")

plt.tight_layout()
plt.show()

    
Seaborn function-গুলো DataFrame-এর column-name string দিয়ে নেয় — কোনো manual df["col"] indexing দরকার নেই। data=df দিন, তারপর x=, y=, hue= column-name।

৪ · histplot ও kdeplot — distribution

একটি variable কীভাবে distributed — histogram বা KDEKernel Density Estimationhistogram-এর smooth version — discrete bin-এর বদলে continuous curve দিয়ে probability density estimate করা হয়। outlier-এ less noisy, আকারে আকর্ষণীয়, কিন্তু bandwidth parameter-এ sensitive। (Kernel Density Estimation)। দু'টি একসাথে দেখানো যায়।

Python · distribution
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="white")
iris = sns.load_dataset("iris")

fig, axes = plt.subplots(1, 3, figsize=(14, 4))

# histogram + KDE overlay
sns.histplot(data=iris, x="petal_length", kde=True, bins=20, ax=axes[0])
axes[0].set_title("Histogram + KDE")

# species-ভেদে KDE
sns.kdeplot(
    data=iris, x="petal_length", hue="species",
    fill=True, alpha=0.4, ax=axes[1]
)
axes[1].set_title("KDE by species — clear separation")

# 2D KDE — joint distribution
sns.kdeplot(
    data=iris, x="sepal_length", y="petal_length",
    fill=True, cmap="Blues", levels=8, ax=axes[2]
)
axes[2].set_title("2D KDE — joint density")

plt.tight_layout()
plt.show()

    
মাঝের plot দেখুন — petal_length-এ setosa পরিষ্কারভাবে আলাদা (অনেক ছোট petal)। এটাই EDA — শুধু দেখেই বুঝে যাবেন এই feature classification-এ অসাধারণ কাজ করবে।

৫ · boxplot ও violinplot — categorical-এ distribution

একটি categorical variable-এর প্রতিটি class-এ continuous variable কেমন distributed — boxplot (median, quartile, outlier) ও violinplot (KDE shape সহ)। ML feature selection-এ অপরিহার্য।

Python · categorical
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid", palette="Set2")
iris = sns.load_dataset("iris")

fig, axes = plt.subplots(1, 2, figsize=(12, 4))

# Boxplot — quartile + outlier
sns.boxplot(
    data=iris, x="species", y="petal_length",
    hue="species", legend=False, ax=axes[0]
)
axes[0].set_title("Boxplot — petal length by species")

# Violinplot — KDE shape সহ
sns.violinplot(
    data=iris, x="species", y="petal_length",
    hue="species", inner="quartile", legend=False, ax=axes[1]
)
axes[1].set_title("Violinplot — distribution shape")

plt.tight_layout()
plt.show()

    
Boxplot — সংক্ষিপ্ত summary (median, IQR)। Violinplot — সম্পূর্ণ density shape। দু'টি modal বা skewed distribution চিনতে violin বেশি কার্যকর।

৬ · heatmap — correlation matrix

HeatmapHeatmap2D matrix-এর প্রতিটি cell-এর value-কে color দিয়ে এনকোড করার plot। সবচেয়ে সাধারণ ব্যবহার — correlation matrix visualization, confusion matrix, এবং attention weight (transformer)। = matrix-এর প্রতিটি cell color-এ। সবচেয়ে জনপ্রিয় ব্যবহার — feature-গুলোর pairwise corr() visualize করা। উচ্চ correlation মানে redundancy → multicollinearity warning।

Python · heatmap
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="white")
iris = sns.load_dataset("iris")

# numeric column-গুলোর correlation
corr = iris.select_dtypes("number").corr()
print(corr.round(2))

plt.figure(figsize=(7, 5))
sns.heatmap(
    corr, annot=True, fmt=".2f",
    cmap="coolwarm", vmin=-1, vmax=1,
    square=True, linewidths=0.5
)
plt.title("Iris — feature correlation heatmap")
plt.tight_layout()
plt.show()

    
petal_length ও petal_width এর correlation ~0.96 — প্রায় redundant feature। ML মডেলে দু'টি একসাথে রাখলে multicollinearity বাড়ে — PCA বা একটিকে drop করার চিন্তা আসে।

৭ · pairplot — সব feature pair-wise

pairplotPairplotএকটি DataFrame-এর সব numeric column-এর pairwise scatter plot এক grid-এ। Diagonal-এ histogram বা KDE। EDA-র জন্য Seaborn-এর সবচেয়ে শক্তিশালী এক-লাইন function। তবে high-cardinality বা মেশানো-type data-তে slow ও দুর্বোধ্য। — EDA-র "ম্যাজিক" এক লাইন। n×n grid: প্রতিটি pair-এর scatter, diagonal-এ distribution। hue দিলে class-ভেদে color। ৪-৫ feature-এ আদর্শ; ১০+ হলে ভীষণ ভিড়।

Python · pairplot
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="ticks")
iris = sns.load_dataset("iris")

# এক লাইনে — সব pair + diagonal-এ KDE + species color
g = sns.pairplot(
    iris, hue="species", diag_kind="kde",
    palette="husl", height=2.0, corner=True   # corner=True → upper triangle বাদ
)
g.fig.suptitle("Iris — pairwise EDA", y=1.02)
plt.show()

    
corner=True — শুধু lower triangle, redundancy কম। diag_kind="kde" — diagonal-এ histogram-এর বদলে smooth density। এই এক plot-এ Iris-এর পুরো structure দেখা যায় — কোন feature class-গুলো আলাদা করে।

৮ · catplot ও relplot — facet grid

Multi-panel — অর্থাৎ একটি condition-ভেদে একই plot বার বার। relplot (relational), catplot (categorical) — figure-level wrapper যা col/row দিয়ে grid বানায়।

Python · facet
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")

# relplot — col ভেদে আলাদা panel
sns.relplot(
    data=tips, x="total_bill", y="tip",
    hue="smoker", col="time", row="sex",
    height=3, aspect=1.2, s=60
)
plt.show()

# catplot — boxplot facet
sns.catplot(
    data=tips, x="day", y="total_bill",
    kind="violin", hue="sex", split=True,
    height=4, aspect=1.5
)
plt.show()

    
col="time" + row="sex" = ২×২ grid। প্রতিটি cell-এ একই scatter plot, ভিন্ন subset। Conditional pattern চোখে পড়ে — যেমন lunch-এ tip-bill সম্পর্ক dinner-এর চেয়ে আলাদা কি?

৯ · Style customization

palette (color), hue (variable mapping), size (third dimension) — visual encoding। sns.color_palette("viridis", 5) দিয়ে নিজস্ব palette।

Seaborn high-level convenience-এর জন্য matplotlib-এর জটিলতা লুকিয়ে রাখে। কিন্তু বড় custom কাজ — multiple subplot-এ আলাদা legend, colorbar position, twin axis — সেখানে ফিরে যেতে হবে matplotlib-এর OO API-তে। Seaborn function-এর return value (Axes বা FacetGrid) ধরে matplotlib operation চালান।

১০ · AI workflow — Iris দিয়ে complete EDA mini

Real EDA workflow — describe → corr → distribution → pairwise → conclusion।

Python · EDA mini
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid", context="notebook")
iris = sns.load_dataset("iris")

# (১) Numerical summary
print("Shape:", iris.shape)
print("\n--- describe ---")
print(iris.describe().round(2))
print("\n--- class balance ---")
print(iris["species"].value_counts())

# (২) Correlation
plt.figure(figsize=(6, 4))
sns.heatmap(
    iris.select_dtypes("number").corr(),
    annot=True, cmap="coolwarm", vmin=-1, vmax=1
)
plt.title("Step 1 — correlation")
plt.tight_layout(); plt.show()

# (৩) Distribution per class
plt.figure(figsize=(8, 4))
sns.violinplot(
    data=iris.melt(id_vars="species", var_name="feature"),
    x="feature", y="value", hue="species", split=False
)
plt.title("Step 2 — feature distribution per class")
plt.xticks(rotation=15)
plt.tight_layout(); plt.show()

# (৪) Pairwise — সবচেয়ে শক্তিশালী
sns.pairplot(iris, hue="species", height=1.8, corner=True)
plt.suptitle("Step 3 — pairwise structure", y=1.02)
plt.show()

# (৫) Insight
print("""
Insight:
- petal_length ও petal_width — class-discriminative (large gap)
- sepal_length/width — কম পার্থক্য, alone দুর্বল
- petal_length ↔ petal_width: corr ~0.96 → multicollinearity
- setosa সম্পূর্ণ আলাদা; versicolor vs virginica কিছু overlap
- সিদ্ধান্ত: petal feature-ই primary; simple model-ই যথেষ্ট
""")

    
Seaborn EDA workflow — DataFrame থেকে modeling সিদ্ধান্ত describe → corr → pairplot → insight → model choice DataFrame pd.read_csv() summary stats describe() + balance corr heatmap sns.heatmap(df.corr()) distribution / boxplot violin + kde by class pairplot sns.pairplot(hue=...) insight feature pick / drop modeling decision — feature, model class, regularization e.g. petal-only LogisticRegression — সহজ ও যথেষ্ট Default styling — Matplotlib বনাম Seaborn Matplotlib default simple, axis-only Seaborn whitegrid grid + palette + hue
উপরে — DataFrame থেকে modeling সিদ্ধান্ত পর্যন্ত Seaborn-চালিত EDA pipeline। নিচে — matplotlib (plain) ও seaborn (whitegrid + palette) default-এর তুলনা।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ Seaborn কেন data analyst-দের প্রিয়? Statistical defaults, less boilerplate, DataFrame-native — তিন দিক বিশ্লেষণ করুন। কখন matplotlib-ই ভাল?

২০১২-তে Michael Waskom যখন Seaborn লেখেন, তখন matplotlib-ই ছিল Python-এর একমাত্র mature plotting library। কিন্তু statistical visualization-এ matplotlib দিয়ে বার বার একই boilerplate লিখতে হতো — error bar, regression line, KDE। Seaborn এই pain point-এর সরাসরি জবাব।

(১) Statistical defaults — সবচেয়ে বড় সুবিধা:

  • regplot — ডেটা দিন, regression line + 95% CI auto। Matplotlib-এ scipy.stats.linregress, manual fitting, manual CI calculation, manual band shading — ১০-১৫ লাইন।
  • kdeplot — bandwidth auto-select, smooth curve। Matplotlib-এ scipy দিয়ে নিজে evaluate, grid বানান, plot।
  • barplot — bootstrap CI auto। boxplot-এ outlier rule auto।
  • উপায়: একই plot তৈরি করতে matplotlib-এ ৫-১০× বেশি কোড।

(২) Less boilerplate — analyst productivity:

  • Color palette ready। Theme এক লাইনে।
  • Legend-এ DataFrame label auto-pickup।
  • Axis label column-name থেকে auto।
  • EDA সেশনে — চিন্তার গতিতে plot। "এই hypothesis test করি" থেকে output ৩০ সেকেন্ডে।

(৩) DataFrame-native API:

  • String column-name দিয়ে কাজ — x="age", hue="dept"। Pandas-এর সাথে natural integration।
  • Long-format ও wide-format দু'টোই handle।
  • melt-করে faceting-এ যাওয়া trivial।
  • Tidy data philosophy-র সাথে aligned (Hadley Wickham-এর R ggplot-এর মতো)।

কখন matplotlib-ই better:

  • Pixel-perfect publication figure: journal submission, custom layout। OO API-এ পূর্ণ control।
  • Interactive widget integration: ipywidgets, custom callback। Seaborn এক layer দূরে।
  • Specialized chart: Sankey, polar, 3D, network — Seaborn cover করে না।
  • Performance critical: ১০ লক্ষ পয়েন্ট scatter — matplotlib direct বা datashader।
  • Animation: FuncAnimation — matplotlib-এর জিনিস।

Hybrid approach — best practice:

  • EDA — Seaborn দিয়ে দ্রুত exploration।
  • Final figure — Seaborn দিয়ে base, তারপর Axes object-এ matplotlib customization।
  • ax = sns.scatterplot(...); তারপর ax.set_xticks(...), ax.annotate(...) — সব কাজ চলে।

মূল উপলব্ধি: Seaborn = "matplotlib + statistics + sane defaults"। যা analyst প্রতিদিন ৮০% কাজে চায় — Seaborn এক লাইনে দেয়। বাকি ২০% custom work-এ matplotlib আছেই — তাই Seaborn ব্যবহার করলেও matplotlib শেখা যায় না এড়ানো।

প্র ০২ Pairplot কেন EDA-র powerhouse? কোন কোন ক্ষেত্রে এটা avoid করবেন — high cardinality, mixed types, large data — তিন scenario বিশ্লেষণ করুন।

sns.pairplot(df, hue="class") — এক লাইন। কিন্তু এই এক লাইন থেকে ML engineer-এর অর্ধেক EDA কাজ হয়ে যায়। Andrew Ng পর্যন্ত Coursera-তে recommend করেন pairplot-এ শুরু করতে।

কেন এত শক্তিশালী:

  • সব pair-এর scatter একসাথে: ৪ feature → ১৬ panel (বা ১০ corner-এ)। সব pairwise relationship চোখে।
  • Diagonal-এ marginal distribution: প্রতিটি feature কেমন distributed — skew, multimodal, outlier।
  • hue দিয়ে class structure: linear vs non-linear separability — visually instant।
  • Cluster, gap, outlier: ML model কত সহজ হবে — পূর্বাভাস।
  • Multicollinearity: দু'টি feature যদি প্রায় linear correlated — সেই scatter দেখলেই বোঝা।

Avoid করুন — তিন scenario:

(ক) High cardinality (অনেক feature):

  • ২০ feature → ৪০০ panel। অপাঠ্য, render slow।
  • সমাধান: প্রথমে correlation heatmap → top-5 informative pick → শুধু সেগুলোর pairplot।
  • অথবা PCA → top-2/3 component-এর pairplot।
  • Production rule: pairplot ৪-৭ feature-এ আদর্শ; ১০-এর বেশি hesitate।

(খ) Mixed types (categorical + numeric মেশানো):

  • pairplot শুধু numeric column ধরে — categorical চুপচাপ skip।
  • Categorical encode করলে (one-hot) — meaningless scatter।
  • সমাধান: numeric-only pairplot + আলাদা catplot categorical-এর জন্য।
  • Best — categorical-কে hue বানান (এক categorical max), বাকিগুলোকে separately treat।

(গ) Large data (অনেক row):

  • ১০ লক্ষ row × ১৬ panel = browser/notebook freeze।
  • Overplotting — সব black blob, কিছু দেখা যায় না।
  • সমাধান:
    • plot_kws={"alpha": 0.05} — transparency।
    • df.sample(5000) — random subsample।
    • kind="kde" বা kind="hist" — density-based।
    • বড় ডেটায় — datashader / hexbin আলাদা tool।

আরও সাবধানতা:

  • Misleading pattern: outlier-এ scatter scale বিকৃত। Robust সিদ্ধান্তে log-transform বা winsorize।
  • Non-linear relationship miss: sin curve scatter-এ "no correlation" দেখায় — কিন্তু সম্পর্ক আছে। correlation coefficient + visual দু'টোই দেখুন।
  • Time series-এ pairplot ভুল tool: sequence ignore। সেখানে line plot, lag plot।

আধুনিক বিকল্প:

  • pandas-profiling / ydata-profiling: এক ক্লিকে full EDA report — pairplot সহ।
  • sweetviz: train vs test comparison সহ pair analysis।
  • Plotly splom: interactive pairplot — zoom, hover।

মূল উপলব্ধি: Pairplot = বিচার শুরুর জায়গা, শেষ নয়। ৪-৬ feature, ১০ হাজার row-এর নিচে — অপ্রতিরোধ্য। তার বাইরে — sample, subset, বা specialized tool। Pattern পেলে — বিশেষ scatter বা boxplot-এ গভীরে যান।

প্র ০৩ Correlation heatmap interpretation — multicollinearity কীভাবে চিনবেন? Spurious correlation কী? Pearson বনাম Spearman correlation — কখন কোনটা?

Correlation heatmap = অর্ধেক EDA। কিন্তু "correlation" শব্দটা সবচেয়ে ভুল-ব্যবহৃত পরিসংখ্যান শব্দ। heatmap দেখে সঠিক সিদ্ধান্ত নিতে কয়েকটা নুয়ান্স জানা চাই।

Multicollinearity — চেনার লক্ষণ:

  • দু'টি feature-এর pearson correlation |r| > 0.8 — সতর্ক হোন।
  • |r| > 0.95 — প্রায় redundant। একটা drop করার চিন্তা।
  • একটি feature অন্যগুলোর linear combination → বিপজ্জনক (perfect multicollinearity)।
  • সঠিক measure: VIF (Variance Inflation Factor) — VIF > ১০ মানে severe।

কেন এটা সমস্যা:

  • Linear regression coefficient unstable → interpretation অসম্ভব।
  • Coefficient sign পর্যন্ত flip করতে পারে।
  • Standard error বিশাল → significance test misleading।
  • Tree-based model কম sensitive, কিন্তু feature importance কৃত্রিমভাবে split।

সমাধান:

  • একটি drop (যেটা domain-এ কম important)।
  • Combined feature (যেমন BMI = weight/height² — দু'টো আলাদা না রেখে)।
  • PCA — orthogonal component।
  • Regularization (Ridge, Lasso) — model-এ tolerate।

Spurious correlation — সবচেয়ে বিপজ্জনক ফাঁদ:

  • "Ice cream sales" ও "drowning death" — উচ্চ correlation। Ice cream drowning ঘটায় না — দু'টোই গরমকালের জন্য।
  • Confounding variable — তৃতীয় কারণ দু'টিকেই চালায়।
  • Selection bias — sample selection process correlation তৈরি করে।
  • Coincidence — Tyler Vigen-এর famous spurious-correlations সাইট দেখুন।
  • Heatmap-এ "0.9 correlation" ≠ "causation"। Domain knowledge অপরিহার্য।

Pearson বনাম Spearman:

  • Pearson r: linear সম্পর্ক পরিমাপ। দু'টি variable-ই continuous, normally distributed হলে সঠিক।
  • Spearman ρ: rank-based — monotonic সম্পর্ক (বাড়ছে কি কমছে, কতটুকু সরাসরি না)। Outlier-এ robust। Non-normal data-তে নিরাপদ।
  • Kendall τ: Spearman-এর চেয়ে আরও robust, কিন্তু ছোট sample।

কোন situation-এ কোনটা:

  • সকল data continuous, normal, linear → Pearson।
  • Outlier আছে, skewed distribution → Spearman।
  • Ordinal data (ranking, Likert scale) → Spearman/Kendall।
  • Non-linear monotonic (e.g., y = x³) → Pearson কম দেখাবে, Spearman সঠিক।
  • Non-monotonic (যেমন U-shape) → কোনোটাই কাজ করবে না; mutual information ব্যবহার।

Heatmap পড়ার চেকলিস্ট:

  1. Diagonal-এ ১.০০ — sanity check।
  2. Symmetric — উপর-নিচ একই।
  3. উচ্চ |r|-এর pair — multicollinearity flag।
  4. Target variable-এর সাথে correlation — feature importance hint।
  5. "All zero column" — variance নেই, drop।
  6. Negative correlation মানেই খারাপ না — শুধু opposite direction।

মূল উপলব্ধি: Heatmap = strong tool, কিন্তু blind use = বিপদ। Multicollinearity-এ structural decision, spurious correlation-এ domain check, distribution-এ Pearson/Spearman বাছাই — তিনটি skill মিলে correct EDA।

প্র ০৪ Modern alternatives — Plotly Express, Altair, Holoviews — interactive ও grammar-of-graphics। Seaborn তবু আজও কেন প্রাসঙ্গিক?

২০১২-র Seaborn এখনো ২০২৬-এর Python data stack-এ সবচেয়ে-ব্যবহৃত statistical visualization library। অথচ এর মধ্যে জন্ম নিয়েছে এক ডজন আধুনিক বিকল্প। তবু seaborn কেন থাকছে — সেই উত্তরে software engineering-এর গভীর শিক্ষা।

আধুনিক বিকল্পগুলো:

  • Plotly Express: interactive (zoom, hover, pan)। DataFrame-native API ঠিক seaborn-এর মতো। HTML output — dashboard, web app-এ আদর্শ। কিন্তু render heavy, static export জটিল।
  • Altair (Vega-Lite): grammar of graphics philosophy। Declarative — "এই data দিয়ে এই encoding"। Beautiful default, JSON-based। কিন্তু ৫,০০০-এর বেশি row-তে slow (default browser limit)।
  • Holoviews + Bokeh: high-level → low-level pipeline। Big data (datashader integration), interactive। Steep learning curve।
  • Plotnine: Python-এ R-ggplot2-র direct port। Grammar of graphics। R community থেকে আসা data scientist-দের প্রিয়।
  • Lets-Plot, ggpy: ggplot-inspired alternatives।

Seaborn-এর তবু টিকে থাকার কারণ:

(১) Static publication-quality:

  • Journal paper, thesis, slide-এ — static PNG/SVG/PDF সবচেয়ে practical।
  • Plotly interactive HTML — print-এ অর্থহীন।
  • Matplotlib backend → vector format pristine।

(২) Statistical-first design:

  • regplot-এর CI band, kdeplot-এর smoothing, barplot-এর bootstrap — built-in statistical primitive।
  • Plotly Express মূলত chart-type, statistics secondary।

(৩) Matplotlib ecosystem-এর সাথে integration:

  • scientific Python-এর সকলেই matplotlib জানে।
  • Seaborn matplotlib-কে replace করে না, augment করে।
  • Notebook ও script — সর্বত্র কাজ। Plotly notebook-centric (HTML)।

(৪) Performance ও simplicity:

  • Lightweight, dependency কম।
  • Static render দ্রুত — research iteration-এ গুরুত্বপূর্ণ।
  • API ছোট, surface area সীমিত — দ্রুত শেখা যায়।

(৫) Cultural inertia (positively):

  • সব ML tutorial, কোর্স, paper — seaborn ব্যবহার করে।
  • Stack Overflow-এ ১০ বছরের answer corpus।
  • Production ML pipeline-এ static plot save — seaborn standard।

কখন আধুনিক alternative-এ যান:

  • Dashboard / web app: Plotly বা Bokeh।
  • Big data interactive: Holoviews + datashader।
  • R থেকে এসেছেন: Plotnine আরামদায়ক।
  • Reproducible declarative spec: Altair → JSON → Vega।
  • Real-time stream: Bokeh server।

হাইব্রিড workflow — modern best practice:

  • EDA + paper figure — Seaborn।
  • Stakeholder dashboard — Plotly Express।
  • Research notebook — দু'টোই, context-অনুযায়ী।
  • Model debugging — TensorBoard, Weights & Biases।

মূল উপলব্ধি: "Newest = best" software engineering-এ ভুল মন্ত্র। Seaborn-এর success আসে narrow scope, deep integration, ও mature ecosystem-এর সমন্বয় থেকে। ২০২৬-এও — static statistical plot-এ এর বিকল্প নেই। যিনি multiple tool know করেন এবং situation-অনুযায়ী বাছেন — তিনিই সেরা analyst।

অনুশীলন

  1. Scatter with hue: sns.load_dataset("penguins") লোড করুন। flipper_length_mm বনাম body_mass_g scatterplot — hue="species" দিয়ে। Title ও legend সহ।
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set_theme(style="whitegrid")
    peng = sns.load_dataset("penguins").dropna()
    
    sns.scatterplot(
        data=peng,
        x="flipper_length_mm", y="body_mass_g",
        hue="species", style="species", s=70
    )
    plt.title("Penguin — flipper vs body mass by species")
    plt.tight_layout()
    plt.show()
  2. Boxplot by category: tips dataset লোড করুন। প্রতিটি day-তে total_bill-এর boxplot। hue="sex" দিয়ে সাব-গ্রুপ।
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set_theme(style="whitegrid", palette="Set2")
    tips = sns.load_dataset("tips")
    
    sns.boxplot(
        data=tips, x="day", y="total_bill", hue="sex",
        order=["Thur", "Fri", "Sat", "Sun"]
    )
    plt.title("Total bill — day-wise & sex-wise")
    plt.tight_layout()
    plt.show()
  3. Correlation heatmap: diamonds বা iris dataset-এর numeric column-এর correlation heatmap তৈরি করুন। Annotation, diverging colormap, সঠিক range সহ।
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set_theme(style="white")
    iris = sns.load_dataset("iris")
    
    corr = iris.select_dtypes("number").corr()
    
    plt.figure(figsize=(6, 5))
    sns.heatmap(
        corr, annot=True, fmt=".2f",
        cmap="coolwarm", vmin=-1, vmax=1,
        square=True, linewidths=0.5,
        cbar_kws={"shrink": 0.8}
    )
    plt.title("Iris — correlation heatmap")
    plt.tight_layout()
    plt.show()
    
    # কোন pair সবচেয়ে multicollinear?
    print(corr.abs().unstack().sort_values(ascending=False).head(8))

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Seaborn pre-installed, এক ক্লিকে dataset access।
🎉 মডিউল ২ শেষ!

L09-L18 — AI-র ডেটা স্ট্যাক সম্পূর্ণ। NumPy (array), Pandas (table), Matplotlib (plot), Seaborn (statistical viz) — চারটি স্তম্ভ। M3-তে এখন কর্মপরিবেশ — Jupyter, Colab, virtual environment, package management।

পূর্ববর্তী পাঠ
পাঠ ১৭ · Matplotlib — প্রথম গ্রাফ