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

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 هي الرسمة كلها.)

كل جزء في الرسمة ليه method على الـ Axes: ax.set_title، و ax.set_xlabel، و ax.legend، وهكذا.

طريقتين للرسم

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()

نفس الصورة 3 مرات. الـ pyplot كويس لبصّة سريعة، بس أول ما يبقى فيه أكتر من chart، "الـ Axes الحالية" بتلخبط.
باقي الدرس بالـ object-oriented: fig, ax = plt.subplots()، وبعدين ax.something(...).

pyplotobject-oriented
plt.title(...)ax.set_title(...)
plt.xlabel(...)ax.set_xlabel(...)
plt.xlim(...)ax.set_xlim(...)
كذا واحدة مرة واحدةax.set(title=..., xlabel=..., ylabel=...)
➕ pandas بترجّع Axes
عشان كده كل اللي في الدرس ده شغال كمان على رسومات pandas: ax = df.plot(...) وبعدين ax.set_title(...).

2الـ Line

ax.plot(x, y) بيوصّل النقط بالترتيب بخطوط مستقيمة.
نقطتين = خط مستقيم واحد. نقط أكتر = مسار. إيراد 2025 كل ربع سنة:

Q1 و Q4 بس

خط طالع: "نمو ثابت".

الأربع أرباع

2.88M، 2.72M، 2.57M، وبعدين 5.51M:
9 شهور ثابتين، وبعدين نطّة في Q4.

نقطتين بيخبّوا كتير.

⚠️ لو اديته list واحدة
ax.plot(monthly.values) بيعتبرها قيم y، ويخترع x = 0، 1، 2، …
يناير بقى عند 0. ادّي الـ x دايمًا.

شكل الخط

كل خط ليه marker، و linestyle، ولون، وتخانة. جرّب:

الـ format string اختصار: الـ marker والخط واللون في string واحد، بأي ترتيب.
"ro" = دواير حمرا من غير خط، "k--s" = خط أسود متقطّع ومربعات.

⚠️ ax.plot(x, y, "o") = markers بس
يعني scatter سريع. من غير format string، الـ plot دايمًا بيوصّل النقط، حتى لو ترتيبها ملوش معنى.

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
y.shape = (m, n), len(x) = m → n linesعدد الـ x لازم يساوي عدد صفوف الـ y، وكل عمود خط

وفيه طريقتين كمان لنفس الرسمة: 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

label= على كل خطax.legend() بيلم كل خط ليه label. الخط اللي من غير label مش هيظهر.
⚠️ ax.legend(["a", "b"])بيسمّي الخطوط بترتيب رسمها، وبيبوظ من غير ما يقولك لو غيّرت ترتيب الكود.
loc="best" (الـ default) بيختار أفضى ركن. "upper left" وأخواتها بيثبّتوه.

شكل كل الرسومات مرة واحدة

الـ 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")
💡 اللي الـ scatter قاله
32 سطر خسرانين، كلهم Electronics، وكلهم بخصم 20%: الخصم الكبير بينزّل السعر تحت التكلفة.

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)
➕ density=True
بيخلّي مساحة كل histogram = 1، فبتقارن الأشكال حتى لو المجموعات أحجامها مختلفة جدًا.

7الـ Bars والـ Pie

ax.bar(categories, heights) بيقارن رقم واحد لكل فئة. 3 عادات بتخلّيه كويس:
رتّب (إلا لو الفئات ليها ترتيب طبيعي زي الشهور)، وأفقي (barh) لو الأسامي طويلة، وابدأ من صفر.
و ax.bar_label(bars) بيكتب القيمة فوق كل bar.

الـ grouped bars: المطب

عايز 2024 جنب 2025 لكل فئة. أول محاولة بتدّي السنتين نفس أسامي الفئات كـ x. جرّب التلات طرق:

⚠️ Matplotlib مفيهاش argument للـ group
كل series بتزقّها بإيدك: لـ series اتنين، كل bar عرضه 0.4، واحد يتزق 0.2 شمال والتاني 0.2 يمين.
النص مبيتزقّش (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 واحدة

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
⚠️ كل رسمة ليها scale لوحدها
ده صح لو بتقارن أشكال (كل الفئات بتعلى في نوفمبر وديسمبر).
لو بتقارن أحجام، شارك المحور بـ 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، وأعلى قيمة)، والقيم الشاذة نقط.
بيقارن عمود رقمي بين فئات كتير من غير زحمة. إيراد السطر حسب الفئة:

الفئةQ1medianQ3max
Stationery120228315630
Accessories1,2842,4004,32012,600
Furniture3,1527,22019,95058,500
Electronics22,05041,80075,600336,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" عشان العناوين متتقصّش.

⚠️ savefig قبل plt.show()
بعد الـ show الـ figure بتتقفل، والصورة اللي هتتحفظ فاضية.

12Case study: الخصم بيكسّب؟

سؤال التخطيط للـ White Friday الجاي: المحل يفضل يدّي 20% خصم؟
الخصم رقم ليه ترتيب (0 ← 5 ← 10 ← 20%)، فخط لكل فئة بيوري الاتجاه، وخط عند الصفر بيوري المحل بيبدأ يخسر فين.

💡 النتيجة والتوصية
الربح بينزل مع الخصم في كل الفئات ما عدا Furniture، اللي بالكاد بتتحرك لحد 20%.
Electronics بتنزل أسرع: من حوالي +10,400 جنيه للسطر من غير خصم، لحوالي −1,750 عند 20%. هامشها رفيع، فالـ 20% بتنزّل السعر تحت التكلفة.
التوصية: نخلّي خصومات الـ White Friday، بس Electronics بحد أقصى 10%.

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

البداية

fig, ax = plt.subplots(figsize=(w, h))

الرسومات

ax.plot · ax.scatter · ax.hist · ax.bar / barh · ax.pie · ax.boxplot

الـ labels

ax.set(title=, xlabel=, ylabel=) · ax.legend() · ax.set_xticks(pos, labels)

كذا رسمة

plt.subplots(r, c, sharey=, layout="constrained") · fig.subplot_mosaic("AAB;CCB")

الكتابة

ax.annotate · ax.text · ax.axhline · ax.axvspan

الحفظ

fig.savefig("x.png", dpi=150, bbox_inches="tight") قبل الـ show