Toma(とま)のゲーム日記

MHNOW、MHWIB、ELDEN RING、WILD HEARTSなどの役立ち情報をアップしていきます。ツイッターでの懸賞応募、自炊、家庭菜園といろいろ始めました。

記事内に商品プロモーションを含む場合があります。

PythonとMatplotlibでグラフを動画化!FuncAnimationによるブログ成長可視化術

ブログの進捗管理において、数値の羅列よりも「動き」のある可視化は、運営者のモチベーションを劇的に引き上げてくれます。 今回は、Pythonスクリプトを使用して、静止画のグラフからドラマチックな2段階アニメーションへと進化させる全プロセスとコードを公開します。

 

1. 実行環境の準備とコマンド

グラフ作成から動画保存まで、スムーズに実行するための環境を整えます。ターミナル(またはコマンドプロンプト)を開き、以下の手順で進めてください。

① Pythonライブラリのインストール

# グラフ作成・データ処理・GIF保存用
pip install matplotlib pandas pillow

② 動画保存用ツール(ffmpeg)のインストール

MP4形式で保存したい場合は、システム全体でffmpegが利用可能である必要があります。OSに合わせたコマンドで導入しましょう。

# Windows (wingetを使用)
winget install ffmpeg

# Mac (Homebrewを使用)
brew install ffmpeg

# Linux (Ubuntu)
sudo apt install ffmpeg

※インストール後、ffmpeg -version でバージョンが表示されれば準備完了です。

2. 【Before】静止画グラフ作成コード

まずは基本となる静止画のグラフです。4,000 PV達成までの軌跡を1枚の画像に凝縮しています。

PythonのMatplotlibで作成したブログ進捗管理グラフ。青い折れ線がPV数、薄青の棒グラフが累計記事数を示し、4K PV達成までの軌跡を赤い注釈で表示している



import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.dates as mdates

# 日本語表示の設定
matplotlib.rc('font', family='MS Gothic')

# 1. データの定義
data = [
    ["4/1 18:23", 0, 0, ""],
    ["4/9 18:09", 1008, 27, "★1K PV達成"],
    ["4/12 10:01", 2018, 42, "★2K PV達成"],
    ["4/17 18:07", 3110, 71, "★3K PV達成"],
    ["4/20 05:54", 4012, 88, "★4K PV達成"]
]

# 2. DataFrameの作成
df = pd.DataFrame(data, columns=['datetime', 'views', 'articles', 'note'])
df['datetime'] = pd.to_datetime('2026/' + df['datetime'], format='%Y/%m/%d %H:%M')

# 3. グラフ作成
fig, ax1 = plt.subplots(figsize=(12, 7))
ax2 = ax1.twinx()

ax1.plot(df['datetime'], df['views'], color='#0000ff', marker='o', linewidth=2.5)
ax2.bar(df['datetime'], df['articles'], color='#aaccff', width=0.3, alpha=0.7)

plt.title('Tomaのゲーム日記:進捗管理(静止画版)')
plt.show()
 

3. 【After】FuncAnimationによる動画生成コード

進化後のコードでは、FuncAnimationを活用し、記事数の積み上げからPVの成長へと繋がる演出を加えています。

Pythonで生成した2段階グラフアニメーション。前半で記事数の積み上げを、後半でPV数の伸びをテロップ付きで動的に表現している



# (アニメーション保存コードを含む最新版)
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.dates as mdates
from matplotlib.animation import FuncAnimation

# 日本語表示の設定
matplotlib.rc('font', family='MS Gothic')

# 1. データ定義(一部抜粋)
data = [
    ["4/1 18:23", 0, 0, ""],
    ["4/9 18:09", 1008, 27, "★1K PV達成"],
    ["4/12 10:01", 2018, 42, "★2K PV達成"],
    ["4/17 18:07", 3110, 71, "★3K PV達成"],
    ["4/20 05:54", 4012, 88, "★4K PV達成"]
]

df = pd.DataFrame(data, columns=['datetime', 'views', 'articles', 'note'])
df['datetime'] = pd.to_datetime('2026/' + df['datetime'], format='%Y/%m/%d %H:%M')

# グラフ初期設定
fig, ax1 = plt.subplots(figsize=(12, 7))
ax2 = ax1.twinx()
n_data = len(df)

def update(frame):
    ax1.clear()
    ax2.clear()
    
    # 共通レイアウト設定
    ax1.set_xlim(pd.Timestamp('2026-04-01'), df['datetime'].max() + pd.Timedelta(days=1))
    ax1.set_ylim(0, 5000)
    ax2.set_ylim(0, 150)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
    
    if frame < n_data:
        # フェーズ1:記事数増加
        curr = df.iloc[:frame+1]
        ax2.bar(curr['datetime'], curr['articles'], color='#aaccff', alpha=0.8)
        ax1.text(0.5, 0.9, '【 フェーズ1:記事数増加状況 】', transform=ax1.transAxes, 
                 ha='center', fontsize=14, fontweight='bold', bbox=dict(facecolor='#f0f0f0'))
    else:
        # フェーズ2:PV数増加
        line_f = frame - n_data
        ax2.bar(df['datetime'], df['articles'], color='#aaccff', alpha=0.3)
        curr = df.iloc[:line_f+1]
        ax1.plot(curr['datetime'], curr['views'], color='#0000ff', marker='o', linewidth=2.5)
        ax1.text(0.5, 0.9, '【 フェーズ2:PV数増加状況 】', transform=ax1.transAxes, 
                 ha='center', fontsize=14, color='#0000ff', fontweight='bold', bbox=dict(facecolor='#eef6ff'))

# アニメーション保存
total_frames = n_data * 2
ani = FuncAnimation(fig, update, frames=total_frames, interval=250)
# ani.save('toma_evolution.gif', writer='pillow', fps=4)
plt.show()

ani.save('toma_growth_progress.gif', writer='pillow', fps=4) # GIF保存
# ani.save('toma_growth_progress.mp4', writer='ffmpeg', fps=4) # MP4保存
 

データの積み上げを「動かす」ことで、日々のブログ運営はもっと楽しくなります。皆さんもぜひ、自分の軌跡をアニメーションにしてみてください!

[Tomaのゲーム日記(はてなブログ)](https://www.tomagamediary.com/)

【AI利用に関する開示】当ブログの一部コンテンツには、AI(人工知能)による執筆支援や画像生成を使用しています。