شكل ومحاور وخط
الرسم أسرع طريقة لترى أن سلسلة الأسعار نظيفة أو ذات اتجاه أو معطوبة. في matplotlib يمثل Figure اللوحة كلها ويمثل Axes رسمًا واحدًا عليها بخطوطه وعناوينه ومفتاحه. والطريقة كائنية التوجه هي fig, ax = plt.subplots() ثم استدعاءات على ax: يرسم ax.plot(x, y) خطًا، وتسمّي ax.set_title وax.set_xlabel وax.set_ylabel الرسم. والرسم على Axes صريح وإعادته يجعلان دالة الرسم سهلة الاستخدام والاختبار.
import matplotlib
matplotlib.use("Agg") # draw without a window (no screen needed)
import matplotlib.pyplot as plt
import pandas as pd
prices = pd.Series([100.0, 102, 101, 105, 107, 106, 110], index=pd.bdate_range("2026-03-02", periods=7))
fig, ax = plt.subplots()
ax.plot(prices.index, prices.values, label="AAPL")
ax.set_title("Closing price")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
print(ax.get_title(), "|", ax.get_xlabel(), "|", ax.get_ylabel()) # Closing price | Date | Price (USD)
print(len(ax.lines), ax.lines[0].get_ydata().tolist()) # 1 [100.0, 102.0, 101.0, 105.0, 107.0, 106.0, 110.0]العناوين ومفتاح الرسم
عند وجود عدة خطوط في رسم واحد يحتاج كل منها إلى اسم. مرّر label="..." إلى ax.plot واستدعِ ax.legend() مرة في النهاية: يسرد المفتاح التسميات بترتيب رسم الخطوط. والرسم بلا تسميات وعنوان ووحدات صورة لا نتيجة. وللخطوط أنماط أيضًا: يعطي linestyle="--" خطًا متقطعًا مناسبًا لمتوسط لا ينبغي أن يحجب الأسعار، وتضبط color وlinewidth وmarker المظهر أكثر.
ma = prices.rolling(3).mean()
ax.plot(ma.index, ma.values, label="MA3", linestyle="--")
ax.legend()
print([line.get_label() for line in ax.lines]) # ['AAPL', 'MA3']
print([text.get_text() for text in ax.get_legend().get_texts()]) # ['AAPL', 'MA3']
print(ax.lines[1].get_linestyle(), ax.lines[1].get_ydata().tolist()[:3]) # -- [nan, nan, 101.0] NaN points are simply not drawnخطوط مرجعية، ورسوم لا تراها
يحدد الخط الأفقي مستوى مثل سعر التنفيذ أو وقف الخسارة أو المتوسط: يرسمه ax.axhline(105, linestyle="--") على عرض الرسم كله (ويفعل axvline ذلك عموديًا). ويستطيع matplotlib الرسم دون أي نافذة: مع الواجهة الخلفية Agg يكتب fig.savefig("chart.png") الرسم في ملف، وهكذا تنتج التقارير والخوادم الرسوم. وبما أن كل ما ترسمه يبقى على كائن Axes فيمكن لبرنامج (أو اختبار) قراءته: الخطوط بـ ax.lines وبياناتها بـ get_ydata() والتسميات بـ get_label() والعنوان بـ get_title().
ax.axhline(105, linestyle=":", label="level")
level_line = ax.lines[-1]
print(list(level_line.get_ydata()), level_line.get_linestyle(), level_line.get_label()) # [105, 105] : level
fig.savefig("prices.png") # writes the chart to a file; no window, no plt.show() needed
plt.close(fig) # release the figure when you are done with itdef plot_prices(prices):
fig, ax = plt.subplots()
ax.plot(prices.index, prices.values)
ax.set_title("Closing price")
return ax # the caller can add lines, save the chart or inspect it
ax = plot_prices(prices)
print(len(ax.lines), ax.get_title()) # 1 Closing price
plt.close("all")plt.subplots() شكله في الذاكرة حتى تستدعي plt.close(fig). وفي حلقة ترسم مئات الرسوم أو في خادم، نسيان ذلك يسرّب الذاكرة ويُطلق تحذيرًا في النهاية. أنشئ الـ Figure داخل الدالة وأعد ما يحتاجه المستدعي ودعه يغلقها.fig, ax = plt.subplots()ثمax.plot(x, y)؛ وسمِّ الرسم بـset_titleوset_xlabelوset_ylabel.- أعطِ كل خط
label=واستدعِax.legend()؛ وlinestyle="--"يرسم خطًا متقطعًا؛ وax.axhline(y)خطًا أفقيًا. - ارسم على Axes وأعده:
ax.linesوget_ydata()وget_label()تقرأ الرسم؛ واستخدمsavefigوplt.closeبدلshowفي البرامج.
التالي: الرسوم الشمعية، لرسم الافتتاح والأعلى والأدنى والإغلاق لكل يوم.
المختبر: ما الذي يُقيَّم
- ارسم خط الأسعار باستخدام
plot_prices25 نقطة - قارن سلسلتين في رسم واحد باستخدام
plot_comparison25 نقطة - أضف متوسطًا متحركًا متقطعًا باستخدام
plot_with_average25 نقطة - ضع علامة على مستوى سعري باستخدام
plot_with_level25 نقطة