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?

MoviePyで作る数学アニメーション入門 : シンプルな関数グラフのアニメーション作成

Posted at

「MoviePyで作る数学アニメーション入門」
数式の動きを動画として作成・視覚化する方法を解説しています。MoviePyとmatplotlibを組み合わせて、パラメータの変化をアニメーション化する手順を一から説明。Python初心者でも簡単に数学関数の動画教材が作れます。🍙

マインドマップ (18).png

はじめに

image.png
数学の概念を視覚的に理解することは、学習効果を高める上で非常に重要です。本記事では、MoviePyを使って数学的なアニメーションを作成する方法を解説します。関数の動的な振る舞いを表現することで、静的な教科書では伝えきれない直感的な理解を促すことができます。

本記事で学べること

image.png

  • MoviePyとmatplotlibを組み合わせた基本的なアニメーション作成方法
  • 関数グラフの動的な表現方法
  • 数学教育コンテンツの作成テクニック

環境設定

必要なライブラリをインストールします:

pip install moviepy
pip install matplotlib
pip install numpy

実装コード

以下のコードでは、二次関数 f(x) = ax² のパラメータ a を時間とともに変化させ、グラフの形状が動的に変化するアニメーションを作成します。

from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(8, 6), dpi=100)

def setup_plot():
    """グラフの基本設定を行う関数"""
    plt.clf()
    plt.grid(True)
    plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
    plt.axvline(x=0, color='k', linestyle='-', alpha=0.3)
    plt.xlim(-5, 5)
    plt.ylim(-2, 10)

def make_frame(t):
    """各フレームを生成する関数"""
    a = t + 0.5
    x = np.linspace(-5, 5, 100)
    y = a * x**2
    
    setup_plot()
    plt.plot(x, y, 'b-', label=f'f(x) = {a:.1f}')
    plt.title(f'Quadratic Function: f(x) = {a:.1f}')
    plt.legend()
    
    fig = plt.gcf()
    canvas = fig.canvas
    canvas.draw()
    width, height = fig.get_size_inches() * fig.get_dpi()
    image = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8)
    image = image.reshape(int(height), int(width), 4)
    return image[:, :, :3]

# アニメーションの作成と保存
duration = 5
animation = VideoClip(make_frame, duration=duration)
animation.write_videofile("quadratic_function.mp4", fps=24)

実行結果の解説

生成される動画では、以下のような変化を観察できます:

  • パラメータ a が時間とともに増加(0.5から5.5まで)
  • 放物線の開きが徐々に大きくなる様子
  • グラフ上部の関数式が動的に更新

応用例とカスタマイズのヒント

異なる関数タイプへの拡張

# 三角関数の例
y = np.sin(a * x)
# 指数関数の例
y = np.exp(a * x)

複数関数の同時表示

plt.plot(x, y1, 'b-', label='function 1')
plt.plot(x, y2, 'r--', label='function 2')

パラメータ変化パターンの変更

# 正弦波による変化
a = 2 + np.sin(t)
# 指数的な変化
a = 0.5 * np.exp(0.5 * t)

まとめ

image.png

MoviePyとmatplotlibを組み合わせることで、数学的な概念を動的に表現するアニメーションを作成できることを学びました。

参考文献とリソース

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?