0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで簡単なアニメーションを作成する方法

Posted at

今回行ったこと

  • matplotlib.animation を使用して、シンプルなアニメーションを作成。
  • データが時間と共に変化する様子を動的に可視化。
  • サイン波が動くアニメーションの例を紹介。

私の環境

  • Python: 3.10.9
  • matplotlib: 3.7.0
  • numpy: 1.23.5

アニメーションの概要

matplotlib.animation モジュールを使うことで、Python のグラフにアニメーションを付けることができます。これにより、データの動的な変化を視覚的に表現することが可能です。たとえば、以下のアニメーションでは、サイン波が徐々に変化していく様子を描画します。


サンプルコード

以下は、サイン波のアニメーションを作成する例です。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

# データ生成
x = np.linspace(0, 2 * np.pi, 100)  # X軸の値
y = np.sin(x)  # 初期のY軸の値

# グラフの初期化
fig, ax = plt.subplots()
line, = ax.plot(x, y, color='blue')

# アニメーションの更新関数
def update(frame):
    line.set_ydata(np.sin(x + frame / 10))  # フレームごとにY軸の値を更新
    return line,

# アニメーション設定
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)

plt.show()

実行結果

以下は、サイン波が徐々に右方向に移動するアニメーションのイメージです。アニメーションは Python スクリプトを実行すると表示されます。

  • フレームの更新: update 関数で、フレームごとにサイン波のデータを動的に変更します。
  • スピード調整: interval パラメータでフレーム間の時間間隔をミリ秒単位で指定可能です。

animation.gif


カスタマイズ例

以下のようなカスタマイズが可能です:

  • 波形を変更
    np.sinnp.cos に変更して、異なる波形をアニメーション化。
  • グラフのスタイル
    ラインの色、スタイル、ラベルを追加して見やすく。
  • フレーム数の増加
    frames の値を大きくすることで、より長いアニメーションを実現。

実用例

  • データの時間変化の可視化
    時系列データがどのように変化するかを直感的に伝えることができます。
  • シミュレーション結果の表現
    数値解析や物理シミュレーションなど、動的なシステムの挙動を再現。
  • 教育用資料
    数学や統計の授業で関数の動きを視覚化して説明する際に便利。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?