Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📊 Week 4 – Visualisation और Storytelling  ·  दिन 22

दिन 22: Seaborn: Distributions और Heatmaps

⏱ 2 hours📶 Intermediate🎯 100% self-study
दिन 22 / 60

✅ आज आप सीखेंगे

  • Matplotlib के ऊपर Seaborn क्यों
  • Distributions: histplot, kdeplot, box, violin
  • Categories: countplot, error bars के साथ barplot
  • Relationships: hue वाला scatterplot, regplot, heatmap
  • एक साथ कई charts: pairplot और FacetGrid

🏢 असली दुनिया में

एक school chain जानना चाहती है: “क्या tuition सच में मदद करती है? घर पर internet वाले students ज़्यादा score करते हैं? Study time ज़्यादा ज़रूरी है या attendance?” Seaborn हर सवाल का जवाब एक line के code से देता है – और अनिश्चितता भी दिखाता है।

Seaborn क्यों?

Matplotlib

  • पूरा control, ज़्यादा code
  • Grouping और aggregation ख़ुद
  • Custom layouts के लिए बढ़िया

Seaborn

  • सीधे DataFrames के साथ
  • hue= अपने आप category से बाँटता है
  • Statistics (mean, CI, KDE) अंदर ही

Distributions

Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
st = pd.read_csv("students_performance.csv")
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
sns.histplot(data=st, x="average", hue="internet", kde=True, ax=ax[0], palette=["#f59e0b", "#4f46e5"])
ax[0].set_title("Students with internet score slightly higher")
sns.kdeplot(data=st, x="study_hours", hue="school_type", fill=True, ax=ax[1], common_norm=False)
ax[1].set_title("Study hours: similar in both school types")
plt.tight_layout(); plt.show()
Internet access के हिसाब से average score का histogram और school type के हिसाब से study hours का KDE
hue= एक chart को groups में बाँट देता है – हाथ से filter करने की ज़रूरत नहीं।
Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
st = pd.read_csv("students_performance.csv")
order = ["School", "Graduate", "Post-Graduate"]
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
sns.boxplot(data=st, x="parent_education", y="average", order=order, ax=ax[0], color="#a5b4fc")
ax[0].set_title("Box plot: median and spread")
sns.violinplot(data=st, x="parent_education", y="average", order=order, ax=ax[1], color="#99f6e4", inner="quartile")
ax[1].set_title("Violin: the full shape")
plt.tight_layout(); plt.show()
Parent education के हिसाब से average score के box और violin plots
Graduate parents के बच्चों का median ऊँचा है, पर groups काफ़ी overlap करते हैं।

Error bars के साथ categories

Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
t = pd.read_csv("telecom_churn.csv")
t["churned"] = (t["churn"] == "Yes").astype(int) * 100
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
sns.countplot(data=t, x="contract", hue="churn", order=["Monthly", "One year", "Two year"], ax=ax[0], palette=["#94a3b8", "#dc2626"])
ax[0].set_title("Customers by contract and churn")
sns.barplot(data=t, x="contract", y="churned", hue="internet_service", order=["Monthly", "One year", "Two year"], ax=ax[1], errorbar=("ci", 95))
ax[1].set_ylabel("Churn %"); ax[1].set_title("Churn % with 95% confidence interval")
plt.tight_layout(); plt.show()
Churn के हिसाब से contracts का countplot और confidence intervals के साथ churn % का barplot
barplot mean और confidence interval दिखाता है – छोटी lines का मतलब ज़्यादा भरोसा।
📏 हर bar पर काली line क्या है?

यह 95% confidence interval है: वह range जिसमें असली औसत शायद है। दो intervals overlap न करें तो अंतर शायद असली है। Day 29 में यह विस्तार से।

Relationships

Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
st = pd.read_csv("students_performance.csv")
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
sns.regplot(data=st, x="study_hours", y="average", ax=ax[0], scatter_kws=dict(s=10, alpha=0.4), line_kws=dict(color="#dc2626"))
ax[0].set_title("Each extra study hour ≈ higher average")
sns.regplot(data=st, x="attendance", y="average", ax=ax[1], scatter_kws=dict(s=10, alpha=0.4, color="#0891b2"), line_kws=dict(color="#dc2626"))
ax[1].set_title("Attendance helps too, but less")
plt.tight_layout(); plt.show()
print(st[["study_hours", "attendance", "average"]].corr().round(2))
study_hours attendance average study_hours 1.00 -0.01 0.79 attendance -0.01 1.00 0.39 average 0.79 0.39 1.00
Study hours और attendance vs average score के regression plots
regplot best-fit line और उसकी अनिश्चितता band बनाता है।
Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
st = pd.read_csv("students_performance.csv")
pv = st.pivot_table(index="parent_education", columns="internet", values="average", aggfunc="mean")
plt.figure(figsize=(5.5, 3.4))
sns.heatmap(pv.loc[["School", "Graduate", "Post-Graduate"]], annot=True, fmt=".1f", cmap="YlGnBu", cbar_kws=dict(label="avg score"))
plt.title("Average score: parent education × internet"); plt.show()
Parent education और internet के हिसाब से average score का heatmap
Pivot table का heatmap दो factors एक साथ दिखाता है।

pairplot और FacetGrid

Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
m = pd.read_csv("mall_customers.csv")
g = sns.pairplot(m[["age", "annual_income_lakh", "spending_score"]], corner=True, plot_kws=dict(s=14, alpha=0.6), height=2.4)
g.figure.suptitle("Mall customers – look at income vs spending!", y=1.02)
plt.show()
Mall customers की age, income और spending score का pairplot
Income × spending panel में पाँच साफ़ groups दिखते हैं – Day 46 में K-Means से इन्हें ढूँढेंगे।
Python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
h = pd.read_csv("house_prices.csv")
g = sns.FacetGrid(h, col="city", col_wrap=3, height=2.6, aspect=1.3)
g.map_dataframe(sns.scatterplot, x="area_sqft", y="price_lakh", hue="furnishing", s=12, palette="Set2")
g.add_legend(); g.set_titles("{col_name}")
plt.show()
हर शहर के area vs price के छोटे charts
Small multiples: हर शहर का वही chart तुलना आसान बनाता है।
💡 एक line में styling

Notebook के ऊपर sns.set_theme(style="whitegrid", palette="muted", font_scale=1.1) हर chart को एक जैसा बना देता है।

🏅 आज के Job Skills

✔ hue से group के हिसाब से distributions✔ Confidence intervals के साथ categories की तुलना✔ regplot और heatmap से relationships✔ pairplot / FacetGrid से कई variables देखना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Telecom data में churn के हिसाब से monthly_charges का box plot। ज़्यादा कौन देता है – जाने वाले या रुकने वाले?
Solution देखें
Python
import pandas as pd, seaborn as sns, matplotlib.pyplot as plt
t = pd.read_csv("telecom_churn.csv")
plt.figure(figsize=(5, 3.5))
sns.boxplot(data=t, x="churn", y="monthly_charges", palette=["#94a3b8", "#dc2626"], hue="churn", legend=False)
plt.title("Churners pay higher monthly charges"); plt.show()
print(t.groupby("churn")["monthly_charges"].median())
churn No 640.0 Yes 790.0 Name: monthly_charges, dtype: float64
Churn के हिसाब से monthly charges का box plot
Program का output
Task 2: Employment type और credit-score band (<650, 650–750, >750) के हिसाब से loan approval rate का heatmap।
Solution देखें
Python
import pandas as pd, seaborn as sns, matplotlib.pyplot as plt
l = pd.read_csv("loan_applications.csv")
l["score_band"] = pd.cut(l["credit_score"], [0, 650, 750, 900], labels=["<650", "650-750", ">750"])
pv = l.pivot_table(index="employment", columns="score_band", values="approved", aggfunc="mean", observed=True) * 100
plt.figure(figsize=(5.5, 3)); sns.heatmap(pv, annot=True, fmt=".0f", cmap="Greens"); plt.title("Approval %"); plt.show()
Loan approval rate का heatmap
Program का output
Task 3: sns.lineplot से Delhi का monthly average AQI दिखाएँ, हर साल की अलग line (hue="year")।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Seaborn में hue="gender"…
हर category का एक रंग।
2. Violin plot box plot से ज़्यादा क्या दिखाता है?
चौड़ाई = उस स्तर पर कितनी values।
3. sns.barplot default में क्या plot करता है?
Counts के लिए countplot; बदलने के लिए estimator=।
4. 4 numeric columns के रिश्ते एक साथ देखने के लिए?
हर जोड़ी का scatter; diagonal पर distributions।
5. Seaborn किस पर बना है?
इसलिए plt.title, ax.set_xlabel आदि सब काम करते हैं।

Interview corner

💼 Interview Corner

दो groups अलग हैं, यह visually कैसे दिखाएँगे?

Distribution के लिए साथ-साथ box या violin plots, और confidence intervals के साथ mean का barplot। Overlap करते intervals बताते हैं कि अंतर शोर हो सकता है – t-test (Day 30) से पक्का करें।

Heatmap कब काम आता है?

Correlation matrix के लिए, या किसी भी two-way table (pivot) के लिए जहाँ ऊँचे-नीचे cells जल्दी पहचानने हों – जैसे contract × internet type के हिसाब से churn।

सारांश

  • Seaborn = Matplotlib के ऊपर DataFrame समझने वाले statistical plots।
  • Distributions के लिए histplot/kdeplot/box/violin; categories के लिए count/barplot।
  • Relationships के लिए regplot और heatmap; कई के लिए pairplot और FacetGrid।
  • Confidence intervals बताते हैं हम कितने निश्चित हैं।
➡️ आगे

Day 23: Plotly – interactive charts जिन पर hover, zoom करके web page की तरह share कर सकते हैं।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Seaborn या Matplotlib – कौन सीखें?
दोनों। तेज़ statistical charts के लिए Seaborn, उन्हें निखारने के लिए Matplotlib – हर Seaborn chart के नीचे Matplotlib chart है।
hue के बिना palette पर FutureWarning क्यों?
नया Seaborn palette देने पर hue चाहता है। hue="वही column" और legend=False जोड़ें।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 23: Plotly Interactive Charts आपकी प्रगति: 22 / 60 (37%) · Lesson 23 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें