【matplotlib】グラフが更新されていくアニメーションを作りたい

Xを見ているとこんな感じでどんどんグラフが更新されていくアニメーションがある。これを作りたくなったのでやってみた。

 

トヨタの株価を取得してアニメーションにしてみました。

実行するにはimagemagickというソフトを入れる必要がありちょっと面倒臭いのですが、出来るようになると楽しいですね!これで色々な化学メーカーの比較をしてみたい。

 

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import yfinance as yf
import matplotlib.dates as mdates 

# トヨタの株価データを取得
toyota_ticker = 'TM'
toyota_data = yf.Ticker(toyota_ticker)

# 日次の株価データを取得し」月次へ変換
toyota_hist = toyota_data.history(start='1980-01-01', end='2023-03-25').resample('M').last()

#グラフの準備
fig, ax = plt.subplots(figsize=(10, 6))
plt.rcParams['font.family'] = 'Meiryo'#フォント指定

def animate(i):
    ax.clear()
    # 1フレームごとのグラフ
    #株価の推移(線)
    ax.plot(toyota_hist["Close"][:i+1], marker='None', linestyle='-', color='b')
    #最新の株価(点)
    ax.plot(toyota_hist[:i+1].index[-1], toyota_hist["Close"][:i+1].iloc[-1], marker='o', color='b', markersize=8, markerfacecolor="white")

    # グラフフォーマット
    ax.set_title('TOYOTA', fontsize=20)#グラフタイトル
    ax.set_ylabel('終値 (USD)', fontsize=20)#Y軸ラベル
    ax.grid(True)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))#X軸ラベルを年表示に
    plt.yticks(fontsize=20)
    plt.xticks(ha="right",fontsize=20)
    plt.subplots_adjust(left=0.15) 

# アニメーションの設定
pause_frames = 20#アニメーションのループの前にポーズを入れる
ani = FuncAnimation(fig, animate, frames=len(toyota_hist)+ pause_frames, interval=1)

# アニメーションの保存
ani_file_path = "toyota_stock_prices_animation3.gif"
ani.save(ani_file_path, writer='imagemagick', dpi=50)