المخططات الخطية والبعثرية
مثّل البيانات المستمرة باستخدام ax.plot() والنقاط المنفصلة باستخدام ax.scatter()، وتحكم في اللون والعلامة ونمط الخط.
المخططات الخطية والبعثرية درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Line and Scatter: Core Plot Types
Line plots connect sequential data points with a line and are ideal for visualising trends over time or continuous functions. Scatter plots draw individual points without connecting lines, making them perfect for exploring relationships between two numeric variables. Both are created on a Matplotlib Axes object: ax.plot() for lines and ax.scatter() for scatter points.
ax.plot() for Line Charts
ax.plot(x, y) draws a line connecting data points in order. Pass x-values as the first argument and y-values as the second. Both can be Python lists, NumPy arrays, or Pandas Series. When only one argument is passed, Matplotlib uses the index (0, 1, 2, ...) as the x-axis automatically. The method returns a list of Line2D Artist objects.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, y) # basic line plot
ax.set_title('Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
# plt.show()
plt.close()Controlling Line Style and Colour
The most common ax.plot() keyword arguments: color (name, hex, or RGB tuple), linewidth (or lw), linestyle (or ls): '-' solid, '--' dashed, ':' dotted, '-.' dash-dot, marker (shape at each data point), and markersize. Combine linestyle and marker to show both the line and the individual data points simultaneously.
fig, ax = plt.subplots(figsize=(7, 4))
# Solid blue line with circle markers
ax.plot(x, np.sin(x), color='steelblue', lw=2, ls='-',
marker='o', markersize=4, label='sin(x)')
# Dashed red line
ax.plot(x, np.cos(x), color='crimson', lw=1.5, ls='--', label='cos(x)')
ax.legend()
plt.close()Plotting Multiple Lines
Call ax.plot() multiple times to overlay several lines on the same Axes. Matplotlib automatically cycles through a default colour palette. Always pass the label keyword for each line so ax.legend() can label them automatically. Place the legend call after all plot calls to ensure all lines are included.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
dates = pd.date_range('2024-01', periods=12, freq='ME')
fig, ax = plt.subplots(figsize=(8, 4))
for product in ['A', 'B', 'C']:
sales = np.random.randint(50, 200, 12)
ax.plot(dates, sales, marker='o', label=f'Product {product}')
ax.set_title('Monthly Sales by Product')
ax.legend()
plt.close()Plotting Pandas DataFrames Directly
Pandas DataFrames have a .plot() method that creates Matplotlib charts directly. Pass ax=ax to draw on an existing Axes object. df.plot(ax=ax) plots all columns as separate lines using the DataFrame index as the x-axis. You can still apply all Matplotlib customisations on the ax object afterward.
df = pd.DataFrame(
np.random.randn(12, 3),
index=pd.date_range('2024', periods=12, freq='ME'),
columns=['North', 'South', 'West']
).cumsum()
fig, ax = plt.subplots(figsize=(8, 4))
df.plot(ax=ax, linewidth=1.5)
ax.set_title('Cumulative Revenue by Region')
ax.set_ylabel('Revenue (cumulative)')
plt.close()ax.scatter() for Scatter Plots
ax.scatter(x, y) draws individual points without connecting lines. Unlike ax.plot(), scatter does not assume the data is ordered. Key parameters: c (colour, can be an array for per-point colouring), s (point size, can also be an array), cmap (colourmap for when c is numeric), alpha (transparency 0-1 to handle overplotting).
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100)
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, color='steelblue', alpha=0.6, s=40)
ax.set_xlabel('Feature X')
ax.set_ylabel('Target Y')
ax.set_title('Feature vs Target')
plt.close()Colouring Scatter Points by Category
Pass a numeric array to the c parameter and a cmap colourmap to colour scatter points by a third variable. Add a colourbar with plt.colorbar(scatter_obj) to provide a scale. This technique is called a bubble chart variant when the s (size) parameter is also varied by a fourth variable.
categories = np.random.choice([0, 1, 2], size=100)
fig, ax = plt.subplots(figsize=(6, 5))
scatter = ax.scatter(x, y, c=categories, cmap='Set1',
alpha=0.7, s=60, edgecolors='none')
fig.colorbar(scatter, ax=ax, label='Category')
ax.set_title('Scatter Coloured by Category')
plt.close()Adding a Trend Line
A scatter plot with a fitted trend line communicates both the individual data points and the overall pattern. Use np.polyfit(x, y, 1) to compute a linear fit, evaluate it with np.poly1d(coeffs)(x_range), and overlay the result with ax.plot() on top of the scatter. The trend line should be thinner and styled differently to distinguish it from data points.
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, alpha=0.4, s=30, color='steelblue', label='Data')
# Fit and plot linear trend line
coeffs = np.polyfit(x, y, 1)
x_line = np.linspace(x.min(), x.max(), 100)
y_line = np.poly1d(coeffs)(x_line)
ax.plot(x_line, y_line, color='red', lw=2, label='Linear fit')
ax.legend()
ax.set_title('Scatter with Trend Line')
plt.close()Shading Confidence Bands with fill_between
ax.fill_between(x, y_lower, y_upper) fills the area between two curves. This is commonly used to show confidence intervals around a mean line, standard deviation bands, or min/max envelopes. Pass alpha to make the shading semi-transparent so the underlying data remains visible.
x_range = np.linspace(0, 2 * np.pi, 100)
mean = np.sin(x_range)
upper = mean + 0.2
lower = mean - 0.2
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_range, mean, color='steelblue', lw=2, label='Mean')
ax.fill_between(x_range, lower, upper,
color='steelblue', alpha=0.2, label='±0.2 band')
ax.legend()
ax.set_title('Line with Confidence Band')
plt.close()Axis Limits and Grid Lines
Control the visible range with ax.set_xlim(min, max) and ax.set_ylim(min, max). Enable grid lines with ax.grid(True). Customise the grid with keyword arguments: linestyle, linewidth, alpha. A subtle grid with alpha=0.3 aids reading exact values without cluttering the chart. Call ax.set_axisbelow(True) to draw the grid behind data points.
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, np.sin(x), 'b-', lw=2)
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.2, 1.2)
ax.grid(True, linestyle='--', alpha=0.5)
ax.set_axisbelow(True) # grid behind data
ax.set_title('Sine with Grid')
plt.close()Alpha and Overplotting
When many data points overlap in the same region of a scatter plot, individual points become invisible — this is called overplotting. The simplest fix is to reduce opacity with alpha (0.0 = fully transparent, 1.0 = fully opaque). Set alpha=0.3 or lower so that dense regions appear darker (because multiple semi-transparent points stack up) while sparse regions remain light. For very large datasets (millions of points), consider hexbin or kernel density estimates instead.
np.random.seed(1)
x_dense = np.random.randn(1000)
y_dense = np.random.randn(1000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Without alpha: overplotting hides density
ax1.scatter(x_dense, y_dense, s=10)
ax1.set_title('No alpha (overplotted)')
# With alpha: density visible
ax2.scatter(x_dense, y_dense, s=10, alpha=0.2)
ax2.set_title('alpha=0.2 (density visible)')
plt.tight_layout()
plt.close()Quick Check
Test your understanding of line and scatter plots in Matplotlib from this lesson.
Lesson Recap
In this lesson you learned: ax.plot() creates line charts with full control over colour, line style, and markers; ax.scatter() creates scatter plots with per-point colour and size via c and s; ax.fill_between() adds confidence bands; and ax.grid() adds grid lines for readability. Next up we create bar charts and histograms to visualise categorical and distributional data.
الأسئلة الشائعة
هل درس «المخططات الخطية والبعثرية» مجاني؟
نعم — نص درس «المخططات الخطية والبعثرية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
ماذا ستتعلم في «المخططات الخطية والبعثرية»؟
مثّل البيانات المستمرة باستخدام ax.plot() والنقاط المنفصلة باستخدام ax.scatter()، وتحكم في اللون والعلامة ونمط الخط. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟
لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.
كم من الوقت يستغرق درس «المخططات الخطية والبعثرية»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟
نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- بنية Figure وAxes
- المخططات الخطية والبعثرية
- المخططات الشريطية والمدرجات التكرارية
- التسميات والعناوين وحفظ الأشكال