→←
Zero Grad · كورس Data Analysis · Visualization

Seaborn

Seaborn قاعدة فوق Matplotlib. بتدّيها الجدول الخام وأسامي الأعمدة،
وهي تعمل الـ grouping، والمتوسط، والألوان، والـ legend.
هنرسم جدول NileCart تاني، المرة دي بـ Seaborn، وبعدين نشوف الرسومات الإحصائية دي بتحسب إيه من ورانا، وبتخبّي إيه.

1Seaborn بتشتغل إزاي

نفس الرسمة بطريقتين: متوسط إيراد السطر لكل فئة.

ax = sns.barplot(data=sales, x="category", y="revenue", errorbar=None)   # the raw table, no groupby
ax.set_title("Mean revenue")                                                 # it's a Matplotlib Axes
data= · x= · y= · hue=الجدول، وأسامي الأعمدة، وعمود للألوان: ده كل Seaborn تقريبًا

نوعين من الـ functions

النوعأمثلةبترسم على
axes-levelscatterplot, lineplot, barplot, histplot, boxplot, heatmapAxes واحدة (ادّيها بتاعتك بـ ax=) وبترجّعها
figure-levelrelplot, catplot, displot, pairplotFigure جديدة فيها panel أو أكتر، وبترجّع FacetGrid

عشان الـ axes-level بترجّع Matplotlib Axes، كل اللي في درس Matplotlib لسه شغال عليها: set_title، و annotate، و axhline، و savefig.

2Relational: scatter و line

ax = sns.scatterplot(data=sales, x="unit_price", y="profit", hue="category", alpha=0.6)   # legend for free
ax.axhline(0, color="black", linewidth=1)

lineplot فيه حاجة لازم تاخد بالك منها: لو فيه سطور كتير لكل x، بيرسم المتوسط، ومعاه band للـ confidence interval 95%.

المتوسط (lineplot على الجدول الخام)

الـ bands بتتداخل تقريبًا في كل حتة: السطر العادي نفس الحجم طول السنة.

الإجمالي (اجمع الأول)

الـ peak بتاع آخر السنة في الإجمالي جاي من أوردرات أكتر، مش أوردرات أكبر.

totals = sales.groupby(["year", "month"], as_index=False)["revenue"].sum()     # for totals, aggregate first
g = sns.relplot(data=totals, x="month", y="revenue", col="year", kind="line", marker="o")  # one panel per year
g.set_titles("{col_name}")

3Categorical: count و bar و box و violin

countplotبيعدّ السطور في كل فئة. order= بيرتّب، و hue= بيقسم كل bar بعمود تاني.
barplotرقم واحد لكل فئة، المتوسط بالـ default، ومعاه error bar.
boxplot / violinplotالتوزيع كله لكل مجموعة: 5 أرقام (box) أو الشكل كله (violin).

الـ barplot بيحسب إيه؟

"مين بيشتري أكتر في الأوردر؟" الكمية في السطر حسب الـ segment. غيّر الـ estimator والـ errorbar:

💡 Corporate بتشتري الضعف
حوالي 6 قطع في السطر، قصاد حوالي 3 لـ Consumer و Small Business. الـ confidence intervals مش متداخلة، فالفرق مش صدفة.

الـ box والـ violin بيورّوا اللي الـ bar بيخبّيه، الانتشار:

sns.boxplot(data=sales, x="category", y="revenue", order=order, log_scale=True)
sns.violinplot(data=sales, x="category", y="revenue", order=order, log_scale=True, inner="quart", cut=0)

4Distribution: histogram و density

gains = sales[sales["profit"] > 0]                          # a log axis needs positive numbers
sns.histplot(data=gains, x="profit", log_scale=True, kde=True)   # log-spaced bins + a smooth curve
sns.histplot(data=known, x="revenue", hue="segment", log_scale=True,
             stat="density", common_norm=False)                 # compare SHAPES of different-size groups
sns.kdeplot(data=known, x="revenue", hue="segment", log_scale=True, fill=True, common_norm=False)

ربح السطر skewed جامد لليمين: الـ median للسطور الكسبانة 1,638 جنيه، وأعلى سطر 64,000.
والـ density: منحنى Corporate على اليمين، يعني السطر النموذجي عندها أغلى (median 5,400، قصاد 3,115 لـ Consumer و 3,425 لـ Small Business).

⚠️ الـ KDE تقدير متنعّم
ممكن يرسم density في حتة مفيهاش داتا خالص. لو شاكك، صدّق الـ histogram.

5الـ hue، والـ palettes، والـ facets

اختار الـ palette على حسب الداتا: "Set2" للفئات، و "viridis" للأرقام المترتّبة، و "RdBu" حوالين نقطة نص.
والـ dict palette مفيدة للتركيز: رمادي لكل حاجة ما عدا المجموعة اللي الرسمة عنها.

highlight = {"Electronics": "#D95D4A", "Furniture": "lightgrey", "Accessories": "lightgrey", "Stationery": "lightgrey"}
sns.barplot(data=sales, x="segment", y="revenue", hue="category", palette=highlight, errorbar=None)

سطر Electronics عند Corporate بيساوي تقريبًا ضعف سطر Consumer.

Facets: لما الـ hue يزحم

نفس الرسمة متكررة، panel لكل مجموعة. col= و row= شغالين في relplot و catplot و displot:

g = sns.catplot(data=sales, x="segment", y="quantity", col="category", col_wrap=2, kind="bar")
g.set_titles("{col_name}")
g.set_axis_labels("Segment", "Mean quantity")

Corporate بتشتري الضعف في كل فئة، مش في فئة واحدة بس.

6Heatmap و pair plot

الـ heatmap جدول ملوّن: pivot table، أو crosstab، أو correlation matrix، والعين بتلاقي الخانات المتطرفة على طول.
annot=True بيكتب الأرقام، و center=0 مع cmap diverging بيحط الخسارة والربح على لونين عكس بعض:

pt = sales.pivot_table(index="category", columns="discount", values="profit", aggfunc="mean")
sns.heatmap(pt, annot=True, fmt=".0f", cmap="RdYlGn", center=0)

corr = sales[["quantity", "unit_price", "discount", "revenue", "profit"]].corr()
mask = np.triu(np.ones_like(corr, dtype=bool))                  # hide the repeated upper triangle
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="RdBu", center=0, vmin=-1, vmax=1)

sns.pairplot(sales[["unit_price", "quantity", "revenue", "profit", "category"]], hue="category", corner=True)

الإيراد ماشي مع سعر القطعة (r = 0.81) أكتر بكتير من الكمية (0.31). والخصم والربح باينين مرتبطين بشكل ضعيف (−0.22)، والجزء الأخير بيوري ليه الرقم ده مضلّل.
الـ pair plot بيعمل scatter لكل اتنين من الأعمدة الرقمية، وتوزيع كل عمود على القطر: أول بصّة على داتا جديدة فيها كام عمود رقمي.

7اقرا الرسومات الإحصائية صح

Seaborn بتحسب quartiles ومتوسطات و intervals من ورا الستارة. إنك تقراها صح مهم قد إنك ترسمها.

الـ box plot متكوّن من إيه؟

الجزءمعناه
الـ boxالنص اللي في النص من السطور، من Q1 لـ Q3 (عرضه هو الـ IQR)
الخط اللي جوهالـ median
الـ whiskersأبعد نقط لسه جوه 1.5 × IQR من الـ box
النقطاللي بعد الـ whiskers: outliers محتملة، تستاهل بصّة، مش أخطاء أوتوماتيك
⚠️ الـ box بيخبّي الشكل
توزيع ليه قمتين بيبان box واحد عادي. لو الشكل مهم، استخدم violin أو histogram.

الـ error bar معناه إيه؟

الـ segmentmeansdعدد السطورCI 95% (±)
Consumer2.991.447620.10
Corporate5.942.535380.21
Small Business3.091.481640.23

CI 95%

بيجاوب: إحنا متأكدين قد إيه من المتوسط؟
1.96 × sd / √n، فبيصغر مع سطور أكتر.

sd

بيجاوب: السطور متفرّقة قد إيه؟
تقريبًا ثابت مهما زوّدت السطور.

يعني الـ CI القصير مش معناه إن العملاء شبه بعض: كميات Corporate بتختلف جامد من سطر لسطر، بس مع العدد ده المتوسط معروف بدقة. قول دايمًا الـ error bar ده إيه.

Overplotting: نقط بتخبّي نقط

correlation واحد ممكن يخبّي أثر المجموعات

قبل ما تقول "مفيش أثر"، قسّم بالمجموعات بـ hue= أو col=.

8الخلاصة في كارت واحد

Relational

scatterplot(hue=, alpha=) · lineplot(hue=, marker=) · relplot(col=)

Categorical

countplot(order=, hue=) · barplot(estimator=, errorbar=) · boxplot · violinplot

Distribution

histplot(log_scale=, kde=, stat="density", common_norm=False) · kdeplot

جداول وكل الأزواج

heatmap(annot=, fmt=, cmap=, center=, mask=) · pairplot(hue=, corner=True)

الشكل

sns.set_theme(style=, palette=) · dict palette للتركيز

اقراها صح

الـ box بيخبّي الشكل · الـ CI عن المتوسط والـ sd عن السطور · النقط بتخبّي بعض · الـ correlation الكلي بيخبّي المجموعات