التسميات والعناوين وحفظ الأشكال
أضف تسميات المحاور والعنوان ووسيلة الإيضاح وتنسيق علامات التدريج، ثم احفظ أشكالًا بجودة مناسبة للنشر باستخدام savefig().
التسميات والعناوين وحفظ الأشكال درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
From Plot to Publication
A chart is only effective if its axes are labelled, its title explains the takeaway, and it is saved at high enough resolution for its intended medium. This lesson covers the finishing touches that transform a quick exploratory plot into a polished figure suitable for a report, dashboard, or academic publication: axis labels, tick formatting, titles, legends, annotations, and file export.
Axis Labels with set_xlabel and set_ylabel
Set descriptive axis labels with ax.set_xlabel() and ax.set_ylabel(). Always include units in the label (e.g., 'Revenue (USD)' rather than just 'Revenue'). Use fontsize to make labels larger for presentations, and labelpad to add space between the axis and the label text when ticks are large.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(7, 4))
x = np.arange(1, 13)
y = np.random.randint(100, 500, 12)
ax.plot(x, y, 'o-', color='steelblue')
ax.set_xlabel('Month', fontsize=12, labelpad=8)
ax.set_ylabel('Revenue (USD thousands)', fontsize=12, labelpad=8)
# plt.show()
plt.close()Titles with set_title and suptitle
ax.set_title() sets the title above a single Axes. For multi-panel figures, fig.suptitle() adds a shared title above all subplots. Control font size with fontsize and vertical position with y (default 1.0). A good title states the main insight of the chart, not just what the axes are — compare 'Monthly Revenue' to 'Revenue Peaked in Q3 and Fell 20% in Q4'.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1,2,3], [1,4,9])
ax1.set_title('Subplot One', fontsize=11)
ax2.bar(['A','B','C'], [3,7,2])
ax2.set_title('Subplot Two', fontsize=11)
# Shared figure title
fig.suptitle('Annual Overview Dashboard', fontsize=14, fontweight='bold', y=1.02)
plt.tight_layout()
plt.close()Controlling Tick Labels
Matplotlib's default tick labels are often adequate, but sometimes you need custom labels. Use ax.set_xticks() to specify tick positions and ax.set_xticklabels() to set the labels. Pass rotation=45 to tilt long labels so they do not overlap. The ha='right' (horizontal alignment) parameter ensures rotated labels anchor correctly to their tick mark.
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
values = np.random.randint(200, 600, 12)
fig, ax = plt.subplots(figsize=(9, 4))
ax.bar(range(12), values, color='steelblue')
ax.set_xticks(range(12))
ax.set_xticklabels(months, rotation=45, ha='right', fontsize=10)
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()Formatting Tick Values
Use matplotlib.ticker formatters to display tick values in a human-readable format. FuncFormatter takes a function that receives the tick value and returns a formatted string. Common patterns: thousands separator, currency symbol, percentage sign, scientific notation. Apply with ax.yaxis.set_major_formatter(formatter).
from matplotlib.ticker import FuncFormatter
def millions_fmt(x, pos):
return f'${x/1e6:.1f}M'
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(['Q1', 'Q2', 'Q3', 'Q4'], [1.2e6, 1.8e6, 2.1e6, 1.9e6], color='steelblue')
ax.yaxis.set_major_formatter(FuncFormatter(millions_fmt))
ax.set_title('Quarterly Revenue')
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()Legends with ax.legend()
Call ax.legend() to display a legend for all plot elements that have a label parameter set. Customise with loc (position, e.g., 'upper right', 'lower left'), ncol (number of columns), framealpha (box transparency), and fontsize. Placing the legend outside the plot area uses bbox_to_anchor combined with loc.
fig, ax = plt.subplots(figsize=(7, 4))
for region, color in [('East','steelblue'),('West','coral'),('North','green')]:
ax.plot(range(12), np.random.randint(100, 400, 12),
marker='o', label=region, color=color)
ax.legend(loc='upper right', ncol=1, framealpha=0.8, fontsize=10)
ax.set_title('Monthly Sales by Region')
plt.close()Adding Text Annotations
ax.annotate(text, xy=(x_point, y_point), xytext=(x_text, y_text), arrowprops=...) adds a text label with an optional arrow pointing to a specific data point. Use this to highlight maximum values, anomalies, or important events on a chart. The arrowprops dict controls the arrow style: arrowstyle='->' is a simple arrow.
y_vals = np.array([120, 180, 310, 250, 420, 380, 290])
x_vals = np.arange(len(y_vals))
peak_idx = np.argmax(y_vals)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_vals, y_vals, 'o-', color='steelblue')
ax.annotate(f'Peak: {y_vals[peak_idx]}',
xy=(peak_idx, y_vals[peak_idx]),
xytext=(peak_idx - 2, y_vals[peak_idx] + 30),
arrowprops={'arrowstyle': '->', 'color': 'red'},
fontsize=10, color='red')
plt.close()Adding Horizontal and Vertical Reference Lines
ax.axhline(y_value) draws a horizontal line across the full width of the Axes at the specified y-value. ax.axvline(x_value) draws a vertical line. Both accept color, linestyle, and linewidth parameters. Reference lines are commonly used to mark targets, thresholds, or event dates on time series charts.
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randint(100, 400, 10), 'o-', color='steelblue')
# Target line
ax.axhline(y=250, color='red', linestyle='--', lw=1.5, label='Target')
# Event line
ax.axvline(x=5, color='orange', linestyle=':', lw=1.5, label='Campaign start')
ax.legend()
ax.set_title('Revenue vs Target')
plt.close()Styling with Themes
Matplotlib includes several built-in style sheets that change the overall look of all figures without code changes: 'seaborn-v0_8-whitegrid', 'fivethirtyeight', 'ggplot', 'bmh', etc. Apply a style with plt.style.use('style_name') at the start of your script. Use plt.style.context('style_name') as a context manager to apply a style only within a block.
# Apply a style globally
plt.style.use('seaborn-v0_8-whitegrid')
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randn(10).cumsum())
ax.set_title('Seaborn Whitegrid Style')
plt.close()
# Reset to default
plt.rcdefaults()Saving Figures with savefig()
fig.savefig('filename.png') saves the figure to a file. Key parameters: dpi (dots per inch — use 150 for screen, 300 for print), bbox_inches='tight' (prevents labels from being clipped), and format (inferred from the extension or specified explicitly). Common formats: '.png' (raster, good for web), '.pdf' (vector, good for print), '.svg' (vector, editable in Illustrator).
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(range(10), np.random.randn(10), 'o-')
ax.set_title('Export Example')
ax.set_xlabel('Step')
ax.set_ylabel('Value')
# Save as PNG (screen quality)
fig.savefig('/tmp/chart_screen.png', dpi=150, bbox_inches='tight')
# Save as PDF (print quality)
fig.savefig('/tmp/chart_print.pdf', dpi=300, bbox_inches='tight')
plt.close()
print('Figures saved.')Complete Example: Polished Report Chart
Here is a complete workflow combining all the techniques in this lesson: a polished time series chart with axis labels, formatted y-axis ticks, a horizontal target line, an annotation on the peak, and export to a high-resolution PNG. This is the pattern you will use for any chart that goes into a report or dashboard.
from matplotlib.ticker import FuncFormatter
fig, ax = plt.subplots(figsize=(9, 5))
months = list(range(1, 13))
revenue = [120, 145, 132, 160, 175, 190, 210, 185, 220, 200, 240, 260]
peak = max(revenue)
peak_idx = revenue.index(peak)
ax.plot(months, revenue, 'o-', color='steelblue', lw=2, markersize=6)
ax.axhline(y=180, color='red', ls='--', lw=1.2, label='Target: $180K')
ax.annotate(f'Peak ${peak}K', xy=(peak_idx+1, peak),
xytext=(peak_idx-1.5, peak+15),
arrowprops={'arrowstyle': '->'}, fontsize=9)
ax.set_xticks(months)
ax.set_xticklabels(['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'], rotation=45, ha='right')
ax.yaxis.set_major_formatter(FuncFormatter(lambda x,p: f'${x:.0f}K'))
ax.set_title('2024 Monthly Revenue vs Target', fontsize=13, fontweight='bold')
ax.set_ylabel('Revenue')
ax.legend()
plt.tight_layout()
plt.close()Quick Check
Test your understanding of labels, titles, and saving figures from this lesson.
Lesson Recap
In this lesson you learned: set_xlabel()/set_ylabel()/set_title() add descriptive text; FuncFormatter formats tick values as currency or percentages; ax.annotate() adds pointed text labels to highlight key data points; axhline()/axvline() draw reference lines; and fig.savefig() with dpi and bbox_inches='tight' produces publication-quality exports. This completes the Matplotlib Fundamentals course — next up is Seaborn for statistical plots.
الأسئلة الشائعة
هل درس «التسميات والعناوين وحفظ الأشكال» مجاني؟
نعم — نص درس «التسميات والعناوين وحفظ الأشكال» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
ماذا ستتعلم في «التسميات والعناوين وحفظ الأشكال»؟
أضف تسميات المحاور والعنوان ووسيلة الإيضاح وتنسيق علامات التدريج، ثم احفظ أشكالًا بجودة مناسبة للنشر باستخدام savefig(). تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟
لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «التسميات والعناوين وحفظ الأشكال»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟
نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- بنية Figure وAxes
- المخططات الخطية والبعثرية
- المخططات الشريطية والمدرجات التكرارية
- التسميات والعناوين وحفظ الأشكال