首页 > 解决方案 > 使用 FuncAnimation 制作 Matplotlib 摆动画的问题

问题描述

我正在模拟的问题是一个简单的钟摆。虽然我在使用 PyGame 之前已经完成了它,但我现在决定使用 matplotlib 的动画工具。它正在工作,但没有达到预期的效果。实时模拟它似乎有效。我调整了帧的间隔和数量,但 fps 太低了。如何在实时播放的同时提高 fps。我将不胜感激。无论如何,这是我的代码:

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

g = 9.80665
L = 2
mu = 0.1
t = 100
theta_0 = np.pi/3
d_theta_0 = 0

def get_d2_theta(theta,d_theta):
    return -mu*d_theta-(g/L)*np.sin(theta)

def theta(t):
    theta = theta_0
    d_theta = d_theta_0
    delta_t = 1./60
    for time in np.arange(0,t,delta_t): 
        d2_theta = get_d2_theta(theta,d_theta)
        theta += d_theta*delta_t
        d_theta += d2_theta*delta_t
    return theta

x_data = [0,0]
y_data = [0,0]

fig, ax = plt.subplots()
ax.set_xlim(-2, 2)
ax.set_ylim(-2.5,1)
line, = ax.plot(0, 0)

def animation_frame(i):
    x = L*np.sin(theta(i))
    y = -L*np.cos(theta(i))

    x_data[1] = x
    y_data[1] = y

    line.set_xdata(x_data)
    line.set_ydata(y_data)
    return line, 

animation = FuncAnimation(fig, func=animation_frame, frames=np.arange(0, 60, (1./60)),interval = 10)
plt.show()

标签: pythonmatplotlibanimationpendulum

解决方案


推荐阅读