Seaborn
Seaborn قاعدة فوق Matplotlib. بتدّيها الجدول الخام وأسامي الأعمدة،
وهي تعمل الـ grouping، والمتوسط، والألوان، والـ legend.
هنرسم جدول NileCart تاني، المرة دي بـ Seaborn، وبعدين نشوف الرسومات الإحصائية دي بتحسب إيه من ورانا، وبتخبّي إيه.
1Seaborn بتشتغل إزاي
نفس الرسمة بطريقتين: متوسط إيراد السطر لكل فئة.
mean_rev = sales.groupby("category")["revenue"].mean() # compute first fig, ax = plt.subplots() ax.bar(mean_rev.index, mean_rev.values) # then draw
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
نوعين من الـ functions
| النوع | أمثلة | بترسم على |
|---|---|---|
| axes-level | scatterplot, lineplot, barplot, histplot, boxplot, heatmap | Axes واحدة (ادّيها بتاعتك بـ ax=) وبترجّعها |
| figure-level | relplot, catplot, displot, pairplot | Figure جديدة فيها 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
الـ barplot بيحسب إيه؟
"مين بيشتري أكتر في الأوردر؟" الكمية في السطر حسب الـ segment. غيّر الـ estimator والـ errorbar:
الـ 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).
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 محتملة، تستاهل بصّة، مش أخطاء أوتوماتيك |
الـ error bar معناه إيه؟
| الـ segment | mean | sd | عدد السطور | CI 95% (±) |
|---|---|---|---|---|
| Consumer | 2.99 | 1.44 | 762 | 0.10 |
| Corporate | 5.94 | 2.53 | 538 | 0.21 |
| Small Business | 3.09 | 1.48 | 164 | 0.23 |
CI 95%
بيجاوب: إحنا متأكدين قد إيه من المتوسط؟
1.96 × sd / √n، فبيصغر مع سطور أكتر.
sd
بيجاوب: السطور متفرّقة قد إيه؟
تقريبًا ثابت مهما زوّدت السطور.
يعني الـ CI القصير مش معناه إن العملاء شبه بعض: كميات Corporate بتختلف جامد من سطر لسطر، بس مع العدد ده المتوسط معروف بدقة. قول دايمًا الـ error bar ده إيه.
Overplotting: نقط بتخبّي نقط
correlation واحد ممكن يخبّي أثر المجموعات
قبل ما تقول "مفيش أثر"، قسّم بالمجموعات بـ hue= أو col=.