شرح بسيط لـ Python Matplotlib Seaborn (مع رسوم بيانية وكود حقيقي)
بايثون ماتبلوتليب سيبورن: الأساسيات في مقال واحد — كود حقيقي، مخططات وخطوات ملموسة، مقتطفات من دورة مكونة من 37 درسًا.
دليل مباشر وموجز: Python Matplotlib Seaborn مفصل مع مخططات ورسوم توضيحية وأوامر مجربة. كل ذلك مستمد من دورة منظمة من 11 فصلاً — إليك أفضل ما فيها.
- مقدمة وتثبيت
- أساسيات Matplotlib
- الرسوم البيانية الأساسية في Matplotlib
- التخصيص والأنماط
- الرسوم الفرعية والأشكال المعقدة
الاستكشاف والتصورات الأولية (EDA)
لماذا EDA قبل لوحة المعلومات؟
في هذا الدرس، سننشئ 5 رسوم بيانية استكشافية لفهم:
الإعداد المشترك
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_theme( style="whitegrid", context="notebook", palette="viridis", font_scale=1.05, ) df = pd.read_csv("ventes_2024.csv", parse_dates=["date"]) print(df.info()) print(df.describe())
الرسم البياني 1: توزيع متوسط السلة
fig, ax = plt.subplots(figsize=(10, 5)) sns.histplot(data=df, x="vente_eur", kde=True, bins=40, color="#7c3aed", ax=ax) mean_vente = df["vente_eur"].mean() median_vente = df["vente_eur"].median() ax.axvline(mean_vente, color="red", linestyle="--", linewidth=2, label=f"Moyenne : {mean_vente:.0f} EUR") ax.axvline(median_vente, color="orange", linestyle="--", linewidth=2, label=f"Mediane : {median_vente:.0f} EUR") ax.set_title("Distribution du panier moyen", fontweight="bold") ax.set_xlabel("Montant de la commande (EUR)") ax.set_ylabel("Nombre de transactions") ax.legend() sns.despine() plt.tight_layout() plt.show()
الرسم البياني 2: تطور الإيرادات الشهرية
monthly = df.groupby("mois").agg( ca=("vente_eur", "sum"), nb_cmd=("vente_eur", "count"), ).reset_index() fig, ax = plt.subplots(figsize=(11, 5)) sns.lineplot(data=monthly, x="mois", y="ca", marker="o", linewidth=2.5, color="#7c3aed", ax=ax) ax.fill_between(monthly["mois"], monthly["ca"], alpha=0.15, color="#7c3aed") best_month = monthly.loc[monthly["ca"].idxmax()] ax.annotate( f"Pic : {best_month['ca']:,.0f} EUR", xy=(best_month["mois"], best_month["ca"]), xytext=(best_month["mois"], best_month["ca"] + 1500), ha="center", fontsize=11, fontweight="bold", color="red", arrowprops=dict(arrowstyle="->", color="red") ) ax.set_title("Evolution mensuelle du chiffre d'affaires 2024", fontweight="bold") ax.set_xlabel("Mois"); ax.set_ylabel("CA (EUR)") ax.set_xticks(range(1, 13)) sns.despine() plt.tight_layout() plt.show()
الرسم البياني 3: الأداء حسب الفئة
cat_perf = df.groupby("categorie").agg( ca=("vente_eur", "sum"), marge=("marge_eur", "sum"), ).reset_index().sort_values("ca", ascending=True) fig, ax = plt.subplots(figsize=(10, 5)) y_pos = range(len(cat_perf)) ax.barh(y_pos, cat_perf["ca"], color="#a78bfa", label="CA", alpha=0.8) ax.barh(y_pos, cat_perf["marge"], color="#7c3aed", label="Marge", alpha=0.9) for i, (ca, marge) in enumerate(zip(cat_perf["ca"], cat_perf["marge"])): ax.text(ca + 2000, i, f"{ca:,.0f} EUR", va="center", fontsize=10, fontweight="bold") ax.set_yticks(y_pos) ax.set_yticklabels(cat_perf["categorie"]) ax.set_title("CA et marges par categorie produit", fontweight="bold") ax.set_xlabel("Montant (EUR)") ax.legend(loc="lower right") sns.despine() plt.tight_layout() plt.show()
الرسم البياني 4: الأداء حسب المتجر (boxplot)
fig, ax = plt.subplots(figsize=(11, 5)) order = df.groupby("magasin")["vente_eur"].median().sort_values(ascending=False).index sns.boxplot(data=df, x="magasin", y="vente_eur", order=order, palette="viridis", hue="magasin", legend=False, ax=ax) sns.stripplot(data=df, x="magasin", y="vente_eur", order=order, color="black", alpha=0.15, size=2, ax=ax) ax.set_title("Distribution des paniers par magasin (trie par mediane)", fontweight="bold") ax.set_xlabel("Magasin"); ax.set_ylabel("Panier (EUR)") sns.despine() plt.tight_layout() plt.show()
الرسم البياني 5: الارتباطات العددية (heatmap)
numeric_cols = ["vente_eur", "marge_eur", "nb_articles", "mois", "trimestre"] corr = df[numeric_cols].corr() fig, ax = plt.subplots(figsize=(8, 6)) sns.heatmap(corr, annot=True, fmt=".2f", cmap="vlag", center=0, square=True, linewidths=0.5, cbar_kws={"shrink": 0.7}, ax=ax) ax.set_title("Matrice de correlation des variables numeriques", fontweight="bold") plt.tight_layout() plt.show()
أول سكريبت تصور
الأهداف التعليمية
import numpy as np وimport matplotlib.pyplot as plt.السكريبت الكامل: 8 أسطر لأول رسم بياني
إليك السكريبت الذي سنفصله معًا. انسخه إلى دفتر Jupyter جديد:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.title("Ma premiere fonction sinus") plt.xlabel("x (radians)") plt.ylabel("sin(x)") plt.grid(True) plt.show()
نفذ الخلية (مفتاح Shift + Enter). يجب أن تظهر منحنى جيبي جميل يتذبذب بين −1 و+1.
التفصيل سطرًا سطرًا
السطران 1-2: الاستيرادات
import numpy as np import matplotlib.pyplot as plt
اتفاقيتان عالميتان:
import matplotlib.pyplot as plt ولا تكتب أبدًا import matplotlib as plt. وحدة pyplot تحتوي على جميع الدوال plot()، title()، إلخ.السطر 3: توليد المحور x
x = np.linspace(0, 2 * np.pi, 100)
np.linspace(بداية، نهاية، n) يعيد مصفوفة من n قيم متباعدة بانتظام بين البداية والنهاية. هنا: 100 نقطة بين 0 و2π (حوالي 6.28).
النتيجة: x = [0.0, 0.063, 0.127, 0.190, ..., 6.283]
السطر 4: حساب y = sin(x)
y = np.sin(x)
يطبق NumPy sin() على كل عنصر من مصفوفة x في عملية واحدة. هذه السحر المتجهي لـNumPy: لا حلقات، سريع جدًا.
النتيجة: y = [0.0, 0.063, 0.127, ..., -0.0]
السطر 5: رسم المنحنى
plt.plot(x, y)
plt.plot(x, y) يرسم خطًا يربط كل نقطة (x[i], y[i]). هذه الدالة الأكثر استخدامًا في Matplotlib كله.
السطور 6-8: العنوان والتسميات والشبكة
plt.title("Ma premiere fonction sinus") plt.xlabel("x (radians)") plt.ylabel("sin(x)") plt.grid(True)
أول رسم بياني خطي ببيانات حقيقية
الأهداف التعليمية
مجموعة بياناتنا: مبيعات شهرية افتراضية
لهذا التمرين، ننشئ DataFrame صغيرًا يحتوي على 12 شهرًا من المبيعات لـ3 منتجات مختلفة:
import pandas as pd import matplotlib.pyplot as plt data = { "Mois": ["Jan", "Fev", "Mar", "Avr", "Mai", "Juin", "Juil", "Aout", "Sep", "Oct", "Nov", "Dec"], "Produit A": [120, 135, 148, 160, 175, 210, 250, 245, 200, 170, 140, 290], "Produit B": [80, 85, 90, 95, 100, 110, 130, 135, 120, 100, 90, 180], "Produit C": [50, 55, 60, 70, 85, 100, 120, 115, 95, 75, 60, 150], } df = pd.DataFrame(data) print(df.head())
النتيجة المعروضة:
Mois Produit A Produit B Produit C 0 Jan 120 80 50 1 Fev 135 85 55 2 Mar 148 90 60 3 Avr 160 95 70 4 Mai 175 100 85
رسم عمود واحد
fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(df["Mois"], df["Produit A"], color="purple", linewidth=2) ax.set_title("Ventes mensuelles du Produit A", fontsize=14) ax.set_xlabel("Mois") ax.set_ylabel("Unites vendues") ax.grid(True, alpha=0.3) plt.tight_layout() plt.show()
تحصل على رسم بياني نظيف يظهر الموسمية في المبيعات (ذروة في يوليو، انفجار في ديسمبر).
رسم عدة سلاسل على نفس الرسم البياني
fig, ax = plt.subplots(figsize=(12, 6)) ax.plot(df["Mois"], df["Produit A"], label="Produit A", linewidth=2, marker="o") ax.plot(df["Mois"], df["Produit B"], label="Produit B", linewidth=2, marker="s") ax.plot(df["Mois"], df["Produit C"], label="Produit C", linewidth=2, marker="^") ax.set_title("Ventes mensuelles par produit", fontsize=14, pad=15) ax.set_xlabel("Mois", fontsize=12) ax.set_ylabel("Unites vendues", fontsize=12) ax.legend(loc="upper left", fontsize=11) ax.grid(True, alpha=0.3) plt.tight_layout() plt.show()
ثلاث تقنيات جديدة مطبقة:
العلامات المتاحة
| الكود | العلامة | الكود | العلامة |
|---|---|---|---|
"o" | دائرة | "s" | مربع |
"^" | مثلث لأعلى | "v" | مثلث لأسفل |
"<"code> | مثلث يسار | ">" | مثلث يمين |
"D" | معين | "d" | معين رفيع |
"*" | نجمة | "+" | زائد |
"x" | تقاطع | "." | نقطة |
"P" | زائد ممتلئ | "X" | تقاطع ممتلئ |
تحميل ملف CSV حقيقي
في الحياة الواقعية، تكون بياناتك في ملف .csv. إليك كيفية تحميله:
# إذا كان الملف في نفس المجلد df = pd.read_csv("ventes.csv") # إذا كان الملف على الويب url = "https://raw.githubusercontent.com/exemple/data/main/ventes.csv" df = pd.read_csv(url) # بفاصل آخر (فاصلة منقوطة) df = pd.read_csv("ventes.csv", sep=";") # مع تحليل تلقائي للتواريخ df = pd.read_csv("ventes.csv", parse_dates=["date"]) print(df.head()) print(df.dtypes)
df.dtypes بعد التحميل. إذا كان عمود متوقع أن يكون رقميًا في object، فهذا يعني وجود فواصل عشرية فرنسية أو خلايا فارغة يجب تنظيفها.نصيحة Pandas + Matplotlib: الاختصار المدمج
لدى Pandas غلاف خاص به لـMatplotlib. يمكنك الرسم مباشرة من DataFrame:
df.set_index("Mois").plot(figsize=(10, 5), marker="o") plt.title("Ventes par produit (style Pandas)") plt.ylabel("Unites") plt.grid(True, alpha=0.3) plt.show()
يغطي هذا المقال المقتطفات الأكثر فائدة — الدورة الكاملة Python Matplotlib Seaborn (11 فصلاً، 37 درسًا، تمارين مصححة ومشروع نهائي) تأخذك إلى النهاية.
./acceder-au-cours-complet cours gratuit : Maîtriser Claude Codeالأسئلة الشائعة
كم من الوقت لتعلم Python Matplotlib Seaborn؟
هل هناك متطلبات مسبقة؟
من أين نبدأ عمليًا؟
📬 هل تريد تلقي هذا النوع من الأدلة كل أسبوع؟ اشترك مجانًا — كود حقيقي، بدون كلام فارغ.