Figure、Axes、そして線
グラフは、価格系列がきれいか、トレンドがあるか、壊れているかを最も手早く確かめる方法です。matplotlib では Figure がキャンバス全体、Axes がその上の1つのグラフで、線・ラベル・凡例を持ちます。オブジェクト指向の書き方は 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]ラベルと凡例
1つのグラフに複数の線を描くときは、それぞれに名前が必要です。ax.plot に label="..." を渡し、最後に ax.legend() を1回呼ぶと、線を描いた順にラベルが凡例に並びます。ラベル・タイトル・単位のないグラフは絵であって結果ではありません。線にはスタイルもあります。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 をメモリに保持します。何百ものグラフを描くループやサーバーでこれを忘れるとメモリがリークし、やがて警告が出ます。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()でグラフを読み戻せる。プログラムではshowの代わりにsavefigとplt.closeを使う
次はローソク足チャートです。毎日の始値・高値・安値・終値を描きます。
ラボ:採点される内容
plot_pricesで価格の折れ線を描く25点plot_comparisonで2つの系列を1つのグラフで比べる25点plot_with_averageで破線の移動平均を加える25点plot_with_levelで価格水準に線を引く25点