【发布时间】:2021-04-29 05:22:36
【问题描述】:
我试图使用钟摆的数学解决方案来制作有趣的动画。我知道我的脚本有点乱,但我真的希望改进。下面是我尝试使用 Matplotlib 中的 FuncAnimation 制作动画。我生成了 3 个点的数据信息,但我的 gif 只显示了一个。
我在这里阅读了与我的问题类似的文档示例和一些答案,但我真的不明白如何在我的案例中应用简单的解决方案。我还看到在这种情况下可以使用散点图,但我仍然无法做到。
考虑到我是使用 Python 的新手,如果您能推荐我一个解决方案,我将不胜感激。如有任何其他关于该脚本的建议,我们将不胜感激。
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from matplotlib.animation import FuncAnimation
%matplotlib inline
def solution(g, length, n, initial_angle, initial_velocity):
# g = 9.81
# l = 9.81
# n = 8
def model(u, t):
return (u[1], - (g / length) * np.sin(u[0] * np.pi / 180))
# Initial angle, and initial velocity
theta0 = [initial_angle, initial_velocity]
# Desired time interval
time = np.arange(0, 2 * n * np.pi, 0.1)
solution = odeint(model, theta0, time)
return solution[:,0]
data = []
for i in range(1, 4):
data.append(solution(9.81, 9.81 * i / 3, n, -17.5, 0))
data = np.array(data)
x_temp = np.sin(data * np.pi / 180)
y_temp = - np.cos(data * np.pi / 180)
# Coordinates for 3 pendulums
for i in range(0, 3):
x_temp[i] = (9.81 * i / 3) * x_temp[i]
y_temp[i] = (9.81 * i / 3) * y_temp[i]
# minimums and maximums based on the longest pendulum
x_min = x_temp[2].min()
x_max = x_temp[2].max()
y_min = y_temp[2].min()
fig, ax = plt.subplots()
ax = plt.axes(xlim=(x_min - 0.5, x_max + 0.5), ylim=(y_min - 0.5, 0))
point, = ax.plot([],[], 'go', lw=3)
# def init():
# point.set_data([], [])
# return point,
def animation_frames(i, x, y):
# point.set_data(x, y)
for j in range(0,3):
point.set_data(x[j][i], y[j][i])
return point,
animation = FuncAnimation(fig, animation_frames, frames=len(x_temp[0]), fargs=(x_temp, y_temp), interval=10)
animation.save('simple_pendulum.gif', writer='imagemagick')
编辑
我按照建议生成了一个简单的案例。在调用 sublopts 函数之前要使用的列表是:
x_tem, y_temp
(array([[-0.98330796, -0.97717458, -0.95882857, -0.92843441, -0.88627296,
-0.83275034, -0.76840839, -0.69393471, -0.61017043, -0.51811348,
-0.41891573, -0.31387291, -0.20440652],
[-1.96661593, -1.9604803 , -1.94210039, -1.91155767, -1.86898966,
-1.81459239, -1.74862365, -1.67140657, -1.58333345, -1.48486936,
-1.37655514, -1.25900948, -1.13292978],
[-2.94992389, -2.94378752, -2.92539636, -2.89480454, -2.85210308,
-2.79742099, -2.73092681, -2.65283041, -2.56338497, -2.46288906,
-2.35168869, -2.23017916, -2.0988066 ]]),
array([[-3.11865443, -3.12058165, -3.12626739, -3.13542813, -3.14760548,
-3.16218704, -3.17843492, -3.19552102, -3.21256783, -3.22869299,
-3.2430556 , -3.2549015 , -3.26360506],
[-6.23730886, -6.2392401 , -6.24498567, -6.25440223, -6.26725439,
-6.28322007, -6.30189776, -6.32281583, -6.34544365, -6.36920427,
-6.39348856, -6.41767054, -6.44112336],
[-9.35596329, -9.35789587, -9.36366147, -9.37316418, -9.38624568,
-9.40268769, -9.42221517, -9.44450056, -9.46916879, -9.49580315,
-9.52395193, -9.55313566, -9.58285505]]))
【问题讨论】:
-
是的,当然。我按照您的建议添加了列表。
标签: python matplotlib animation