記事ディレクトリ
概要
まず、数学演算用の NumPy やデータ視覚化用の Matplotlib ライブラリなど、必要なライブラリをインポートします。次に、グラフと軸を作成し、点の位置を初期化し、初期化関数と更新関数を作成します。
初期化関数は、座標軸の範囲などを含むグラフの初期状態を設定します。 update 関数はアニメーションの各フレームの変化を定義するもので、ここでは cos 関数を例としてポイントの新しい座標位置を計算します。
FuncAnimation クラスを通じて、アニメーションのフレーム番号、初期化関数、更新関数、その他のパラメーターを設定し、最後に plt.show() を呼び出してアニメーションを表示します。
背景画像の生成
アニメーションを描画する前に、まず cos 関数の背景画像を生成する必要があります。この手順は非常に簡単で、通常 Matplotlib を使用してプロットする方法と似ています。
import numpy as np
import matplotlib.pyplot as plt
def generate_background():
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
# 创建图形并绘制cos函数
fig = plt.figure()
plt.plot(x, y)
# 添加网格线
plt.grid(ls='--')
# 保存生成的背景图
plt.savefig("cos_background.png")
# 显示图形(可选)
plt.show()
# 调用函数生成背景图
generate_background()
ポイントアニメーションを追加する
このステップでは、アニメーション ライブラリを使用して、アニメーション ポイントをコードに追加します。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_points(num):
point_ani.set_data(x[num], y[num])
return point_ani,
def add_animation_points():
global point_ani, x, y
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
# 创建图形并绘制cos函数
fig = plt.figure()
plt.plot(x, y)
# 初始化动画点
point_ani, = plt.plot(x[0], y[0], "ro")
# 添加网格线
plt.grid(ls="--")
# 创建动画
ani = animation.FuncAnimation(fig, update_points, np.arange(0, 100), interval=100, blit=True)
# 保存动画为gif文件
ani.save('cos_animation.gif', writer='imagemagick', fps=10)
# 显示动画(可选)
plt.show()
# 调用函数添加动画点
add_animation_points()
説明する:
上記のコードでは、最初に update_points という関数が定義されており、プロットされたイメージ内のデータ ポイントを更新するために使用されます。関数の入力パラメータ num は現在のアニメーションのフレームを表し、関数の戻り値は更新する必要があるオブジェクトです。
次に、この関数を FuncAnimation 関数に渡します。その主なパラメータは次のように導入されます。
fig: 当前绘图对象
update_points: 更新动画的函数
np.arange(0, 100): 动画帧数,这里需要是一个可以迭代的对象
interval: 动画的时间间隔
blit: 是否开启动画渲染
最後に、アニメーションを GIF ファイルとして保存し、オプションでアニメーション効果を表示します。
テキスト表示を追加する
上記のコードは、単純なポイント アニメーション効果を実装しています。 `
上記のコードを少し変更して、テキストの表示をサポートし、さまざまな条件下でさまざまなポイント スタイルを表示することができます。
上記の効果は、update_points 関数に追加のコード ロジックを追加することで実現できます。
def update_points_v3(num):
point_ani.set_data(x[num], y[num])
if num % 5 == 0:
point_ani.set_marker("*")
point_ani.set_markersize(12)
else:
point_ani.set_marker("o")
point_ani.set_markersize(8)
text_pt.set_position((x[num], y[num]))
text_pt.set_text("x=%.2f, y=%.2f" % (x[num], y[num]))
return point_ani, text_pt,
完全なコード:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_points(num):
point_ani.set_data(x[num], y[num])
text_pt.set_position((x[num], y[num]))
text_pt.set_text("x=%.2f, y=%.2f" % (x[num], y[num]))
return point_ani, text_pt
def update_points_v2(num):
# 每隔5帧改变点的样式
if num % 5 == 0:
point_ani.set_marker("*")
point_ani.set_markersize(12)
else:
point_ani.set_marker("o")
point_ani.set_markersize(8)
# 更新动画点和文本显示
point_ani.set_data(x[num], y[num])
text_pt.set_position((x[num], y[num]))
text_pt.set_text("x=%.2f, y=%.2f" % (x[num], y[num]))
return point_ani, text_pt
def add_animation_points():
global point_ani, text_pt, x, y
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
# 创建图形并绘制cos函数
fig = plt.figure()
plt.plot(x, y)
# 初始化动画点和文本
point_ani, = plt.plot(x[0], y[0], "ro")
text_pt = plt.text(x[0], y[0], "x=%.2f, y=%.2f" % (x[0], y[0]), ha='right', va='bottom')
# 添加网格线
plt.grid(ls="--")
# 创建动画
ani = animation.FuncAnimation(fig, update_points_v2, np.arange(0, 100), interval=100, blit=True)
# 保存动画为gif文件
ani.save('cos_animation.gif', writer='imagemagick', fps=10)
# 显示动画(可选)
plt.show()
# 调用函数添加动画点
add_animation_points()
結果
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 定义常量
g = 9.8 # 重力加速度
length = 1.0 # 钟摆长度
theta0 = np.pi / 4.0 # 初始摆角
time_interval = 0.05 # 时间间隔
# 计算角速度
omega0 = 0.0
omega = omega0
# 初始化时间和角度
t = 0.0
theta = theta0
# 创建画布和子图
fig, ax = plt.subplots()
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
# 初始化绘制的对象
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
# 更新函数,用于每一帧的绘制
def update(frame):
global theta, omega, t
# 计算新的角度和角速度
alpha = -g / length * np.sin(theta)
omega += alpha * time_interval
theta += omega * time_interval
# 更新绘制的数据
x = [0, length * np.sin(theta)]
y = [0, -length * np.cos(theta)]
line.set_data(x, y)
# 更新时间文本
t += time_interval
time_text.set_text(time_template % t)
return line, time_text
# 创建动画
ani = animation.FuncAnimation(fig, update, frames=range(0, 100), interval=time_interval * 1000, blit=True)
# 显示动画
plt.show()
まとめ
cos 関数を例として説明し、cos 曲線に沿って移動する点のアニメーション効果を段階的に実現します。
物理モデル: 単純な物理モデルを使用して説明します。 2 つの相互接続された振り子システム。各振り子は重力の影響を受け、最初の振り子の動きは 2 番目の振り子に伝達されます。
数学的モデリング: 角速度、角度、ニュートンの運動方程式などの単純な物理方程式を適用して、振り子の運動をモデル化します。
Matplotlib のアニメーション クラス: Matplotlib のアニメーション クラスを使用すると、振り子の位置が更新され、各フレームに描画されます。定期的な更新により、鮮やかな振り子スイングのアニメーション効果が得られます。
インタラクティブな表示: Matplotlib の plt.show() 関数を使用すると、アニメーションをグラフィカル インターフェイスにリアルタイムで表示でき、ユーザーは振り子の動きを観察できます。