文章目錄
- 概要
- 生成背景圖
- 添加點動畫
- 添加文本顯示
- 小結
概要
首先,通過導入必要的庫,包括NumPy用于數學運算和Matplotlib庫用于數據可視化。隨后,創建圖形和軸,初始化點的位置,以及編寫初始化函數和更新函數。
初始化函數負責設置圖形的初始狀態,包括坐標軸的范圍等。更新函數則定義了動畫每一幀的變化,這里以cos函數為例,計算點的新坐標位置。
通過FuncAnimation類,設置動畫的幀數、初始化函數、更新函數等參數,最后調用plt.show()顯示動畫。
生成背景圖
在繪制動畫之前,首先需要生成cos函數的背景圖。這個步驟非常簡單,與通常使用Matplotlib進行繪圖的方法相似。
import numpy as np
import matplotlib.pyplot as pltdef 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()
添加點動畫
這一步使用animation庫,往代碼里添加動畫點。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animationdef update_points(num):point_ani.set_data(x[num], y[num])return point_ani,def add_animation_points():global point_ani, x, yx = 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 animationdef 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_ptdef 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_ptdef add_animation_points():global point_ani, text_pt, x, yx = 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_intervaltheta += omega * time_interval# 更新繪制的數據x = [0, length * np.sin(theta)]y = [0, -length * np.cos(theta)]line.set_data(x, y)# 更新時間文本t += time_intervaltime_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曲線運動的動畫效果
物理模型: 使用了簡單的物理模型描述了兩根相互連接的鐘擺系統。每根鐘擺都受到重力的作用,同時第一根鐘擺的運動會傳遞給第二根鐘擺。
數學建模: 應用了簡單的物理方程,包括角速度、角度和牛頓的運動方程,來模擬鐘擺的運動。
Matplotlib的Animation類: 利用Matplotlib的Animation類,實現了每一幀鐘擺位置的更新和繪制。通過定時更新,我們得到了一個生動的鐘擺擺動的動畫效果。
交互式展示: 使用Matplotlib的plt.show()函數,動畫可以在圖形界面中實時展示,方便用戶觀察鐘擺的運動。