Matplotlib
Matplotlib هي المكتبة اللي تحت أغلب الرسومات في Python:
الـ .plot() بتاع pandas و Seaborn الاتنين بيرسموا بيها.
في الدرس ده هنحوّل جدول مبيعات NileCart لـ charts: lines، و scatter، و histograms، و bars،
وبعدين نحط كذا chart في figure واحدة، ونكتب عليها، ونحفظها.
1الـ Figure والـ Axes
كلمتين هتشوفهم في كل رسالة error من Matplotlib:
Figure
الصورة كلها، اللوحة اللي بنرسم عليها.
ممكن تشيل chart واحد أو كذا chart.
Axes
chart واحد جوه الـ Figure، ليه محور x ومحور y، وداتا، وعنوان، و legend.
(مش "axis": الـ Axes هي الرسمة كلها.)
طريقتين للرسم
plt.plot(monthly.index, monthly.values) # plt.* draws on "the current Axes" plt.title("Revenue by month") plt.show()
fig, ax = plt.subplots() # hold the Figure and the Axes ax.plot(monthly.index, monthly.values) # and call their methods ax.set_title("Revenue by month") plt.show()
ax = monthly.plot(marker="o", title="Revenue by month") # pandas draws with Matplotlib type(ax) # matplotlib Axes
نفس الصورة 3 مرات. الـ pyplot كويس لبصّة سريعة، بس أول ما يبقى فيه أكتر من chart، "الـ Axes الحالية" بتلخبط.
باقي الدرس بالـ object-oriented: fig, ax = plt.subplots()، وبعدين ax.something(...).
| pyplot | object-oriented |
|---|---|
| plt.title(...) | ax.set_title(...) |
| plt.xlabel(...) | ax.set_xlabel(...) |
| plt.xlim(...) | ax.set_xlim(...) |
| كذا واحدة مرة واحدة | ax.set(title=..., xlabel=..., ylabel=...) |
2الـ Line
ax.plot(x, y) بيوصّل النقط بالترتيب بخطوط مستقيمة.
نقطتين = خط مستقيم واحد. نقط أكتر = مسار. إيراد 2025 كل ربع سنة:
Q1 و Q4 بس
خط طالع: "نمو ثابت".
الأربع أرباع
2.88M، 2.72M، 2.57M، وبعدين 5.51M:
9 شهور ثابتين، وبعدين نطّة في Q4.
نقطتين بيخبّوا كتير.
يناير بقى عند 0. ادّي الـ x دايمًا.
شكل الخط
كل خط ليه marker، و linestyle، ولون، وتخانة. جرّب:
الـ format string اختصار: الـ marker والخط واللون في string واحد، بأي ترتيب.
"ro" = دواير حمرا من غير خط، "k--s" = خط أسود متقطّع ومربعات.
3كذا خط
أغلب الأسئلة مقارنات: 2025 كسبت 2024؟ أسهل طريقة: ax.plot مرتين.
أو array بعدين: كل عمود بيبقى خط. pivot table صفوفها الشهور وأعمدتها السنين هي بالظبط كده:
pv = sales.pivot_table(index="month", columns="year", values="revenue", aggfunc="sum") pv.shape # (12, 2): 12 x-positions, 2 lines ax.plot(pv.index, pv.values) # x matches the ROWS of y ax.plot(pv.index, pv.values.T) # ValueError: x and y must have same first dimension
وفيه طريقتين كمان لنفس الرسمة: ax.plot(x, y1, "o-", x, y2, "s--") في call واحد،
أو اختصار pandas pv.plot(marker="o")، اللي بيحط الـ legend كمان.
4عناوين، و labels، و legend، و ticks
الرسومات اللي فاتت كويسة للاستكشاف، بس مش لحد تاني: مفيش عنوان، ولا وحدات، والشهور 2، 4، 6، ومش عارف أنهي خط أنهي سنة. نفس الرسمة متشطّبة:
fig, ax = plt.subplots(figsize=(10, 4)) ax.plot(pv.index, pv[2024], "o-", color="#9AA5B1", label="2024") ax.plot(pv.index, pv[2025], "o-", color="#0F766E", lw=2.5, label="2025") ax.set_title("Monthly revenue: the end-of-year peak repeats") ax.set_xlabel("Month") ax.set_ylabel("Revenue (EGP)") ax.set_xticks(range(1, 13), month_names) # positions, then the labels ax.set_ylim(0, None) # start the y-axis at 0 ax.yaxis.set_major_formatter("{x:,.0f}") # 2500000 -> 2,500,000 ax.grid(True, axis="y", alpha=0.3) ax.legend(title="Year", loc="upper left")
الـ legend
شكل كل الرسومات مرة واحدة
الـ style بيغيّر شكل كل رسمة بعده: plt.style.use("ggplot")، أو لبلوك واحد بس: with plt.style.context("ggplot"):.
وتحت كل style فيه plt.rcParams، dictionary كبير بالـ defaults. تظبطه مرة في أول النوت بوك، وكل الرسومات تاخد نفس الشكل:
plt.rcParams.update({
"figure.figsize": (8, 4.5),
"axes.spines.top": False, "axes.spines.right": False, # no box around the plot
"axes.grid": True, "grid.alpha": 0.3,
"axes.formatter.limits": (-7, 9), # plain numbers, no "1e6"
"axes.prop_cycle": mpl.cycler(color=["#0F766E", "#E89B2D", "#D95D4A"]),
})
5الـ Scatter
الـ bars والـ lines بيورّوا رقم واحد لكل مجموعة. الـ scatter بيوري كل سطر كنقطة، برقمين على x و y:
الـ chart بتاع "ده ماشي مع ده؟". الأوردر الأكبر معناه ربح أكبر؟
for cat, part in sales.groupby("category"): # one call per group = a legend for free ax.scatter(part["revenue"], part["profit"], label=cat, alpha=0.6, s=20) points = ax.scatter(elec["revenue"], elec["profit"], c=elec["discount"], cmap="viridis", s=elec["quantity"] * 15) # colour and size from numbers fig.colorbar(points, ax=ax, label="discount")
6الـ Histogram
"الأوردر العادي شكله إيه؟" سؤال عن توزيع رقم واحد. الـ histogram بيقطّع المدى لـ bins ويعدّ القيم في كل واحد.
مش bar chart: الـ bar بيقارن فئات، والـ histogram الـ bars بتاعته لازقة في بعض لأن الـ bins متصلة.
عدد الـ bins بيغيّر الصورة: قليل بيخبّي الشكل، وكتير بيحوّله noise. جرّب كذا قيمة دايمًا.
وللفلوس، الـ log axis غالبًا هو الصح: كل خطوة ×10 بدل +10,000، فالكشكول بـ 45 جنيه واللابتوب بـ 300,000 الاتنين باينين.
بس الـ bins لازم تبقى متساوية على الـ log، وده اللي np.logspace بيعمله:
log_bins = np.logspace(np.log10(rev.min()), np.log10(rev.max()), 30) ax.hist(rev, bins=log_bins, edgecolor="white") ax.set_xscale("log") for cat in ["Accessories", "Furniture", "Electronics"]: # compare groups: overlap them ax.hist(rev[sales["category"] == cat], bins=log_bins, alpha=0.5, density=True, label=cat)
7الـ Bars والـ Pie
ax.bar(categories, heights) بيقارن رقم واحد لكل فئة. 3 عادات بتخلّيه كويس:
رتّب (إلا لو الفئات ليها ترتيب طبيعي زي الشهور)، وأفقي (barh) لو الأسامي طويلة، وابدأ من صفر.
و ax.bar_label(bars) بيكتب القيمة فوق كل bar.
الـ grouped bars: المطب
عايز 2024 جنب 2025 لكل فئة. أول محاولة بتدّي السنتين نفس أسامي الفئات كـ x. جرّب التلات طرق:
النص مبيتزقّش (cy.index - 0.2 = TypeError)، فالأماكن بتبقى الأرقام 0، 1، 2، 3، و set_xticks بيرجّع الأسامي.
pandas بتعملها في سطر: cy.plot(kind="bar")، و stacked=True للـ stacked.
الـ pie لأجزاء من كل واحد، ولعدد قليل من الشرايح بس. bar مترتّب غالبًا أوضح (شوف درس ليه نرسم). لـ 5 مناطق مقبول: ax.pie(values, labels=..., autopct="%1.1f%%", startangle=90).
8كذا رسمة في figure واحدة
plt.figure(figsize=(10, 3.5)) plt.subplot(1, 2, 1) # 1 row, 2 columns, plot 1 (counts from 1!) plt.barh(segments.index, segments.values) plt.subplot(1, 2, 2) # plot 2 plt.hist(sales["quantity"], bins=10)
fig, axs = plt.subplots(2, 2, figsize=(10, 6), sharex=True, layout="constrained") for ax, cat in zip(axs.flat, categories): # axs is an array of Axes ax.plot(by_cat_month.index, by_cat_month[cat], marker="o") ax.set_title(cat) fig.suptitle("Monthly revenue by category") # one title for the whole figure
لو بتقارن أحجام، شارك المحور بـ sharey=True: Electronics بالملايين، و Stationery بتبقى خط مفرود.
Layouts مش متساوية
subplot_mosaic بترسم الـ layout كنص: كل حرف رسمة، والحرف المتكرر بيكبّر رسمته. اكتب الـ mosaic بنفسك:
نفس الفكرة بـ plt.subplot: كل call بيتخيّل grid لوحده. subplot(2, 1, 1) = النص اللي فوق كله، و subplot(2, 3, 4) و 5 و 6 = الصف اللي تحت.
9الـ Box plot
ملخّص التوزيع في 5 أرقام (أقل قيمة، و Q1، و median، و Q3، وأعلى قيمة)، والقيم الشاذة نقط.
بيقارن عمود رقمي بين فئات كتير من غير زحمة. إيراد السطر حسب الفئة:
| الفئة | Q1 | median | Q3 | max |
|---|---|---|---|---|
| Stationery | 120 | 228 | 315 | 630 |
| Accessories | 1,284 | 2,400 | 4,320 | 12,600 |
| Furniture | 3,152 | 7,220 | 19,950 | 58,500 |
| Electronics | 22,050 | 41,800 | 75,600 | 336,000 |
groups = [sales.loc[sales["category"] == c, "revenue"] for c in order] # one list per group bp = ax.boxplot(groups, tick_labels=order, vert=False, patch_artist=True, showfliers=False) for box, color in zip(bp["boxes"], ["lightblue", "khaki", "salmon", "lightgreen"]): box.set_facecolor(color) # patch_artist=True makes boxes fillable ax.set_xscale("log")
الـ median بتاع Electronics 41,800 جنيه، و Stationery 228: عشان كده الـ log scale لازم.
10كتابة على الرسمة، ومحاور التواريخ
لما يبقى فيه حاجة واحدة لازم القارئ يشوفها، اكتبها عليها:
ax.annotate(f"Peak: {peak_val:,.0f}", xy=(peak_date, peak_val), # the point xytext=(pd.Timestamp("2024-05-01"), peak_val), # where the text goes arrowprops={"arrowstyle": "->"}) ax.axhline(average, color="grey", linestyle=":") # a reference line ax.text(x, y, "monthly average") # plain text ax.axvspan(pd.Timestamp("2024-11-01"), pd.Timestamp("2024-12-31"), alpha=0.15) # shade a period
أعلى شهر: ديسمبر 2024، 2,670,815 جنيه.
محور التواريخ
سنتين إيراد يومي = 731 نقطة، والـ ticks الافتراضية بتبقى زحمة.
الـ locator بيقرر فين الـ ticks، والـ formatter بيقرر شكلها:
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3)) # a tick every 3 months ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y")) # Jan 2024 fig.autofmt_xdate() # tilt the labels smooth = daily.rolling(30, center=True).mean() # a 30-day average shows the trend
11الحفظ
fig.savefig("output/revenue_by_region.png", dpi=150, bbox_inches="tight") plt.show()
الامتداد بيحدد النوع: .png للسلايدز والرسايل، و .svg أو .pdf للطباعة. و bbox_inches="tight" عشان العناوين متتقصّش.
12Case study: الخصم بيكسّب؟
سؤال التخطيط للـ White Friday الجاي: المحل يفضل يدّي 20% خصم؟
الخصم رقم ليه ترتيب (0 ← 5 ← 10 ← 20%)، فخط لكل فئة بيوري الاتجاه، وخط عند الصفر بيوري المحل بيبدأ يخسر فين.
Electronics بتنزل أسرع: من حوالي +10,400 جنيه للسطر من غير خصم، لحوالي −1,750 عند 20%. هامشها رفيع، فالـ 20% بتنزّل السعر تحت التكلفة.
التوصية: نخلّي خصومات الـ White Friday، بس Electronics بحد أقصى 10%.