我想创建一个动画,显示潜水员跳入水中。
通过水的潜水员原始高度的给定参数h
和他的质量m
,我在Python中定义了一个程序来计算他接触水的时刻,{{1} }。
知道他垂直跳跃,X轴是固定的,并且 Y轴服从方程(1/2) g t ^ 2 + h(g是引力常数)
如果时间Tc
在范围内(t
),我如何绘制图表,X轴和Y轴显示潜水员的投影? (Tc
已修复且x
取决于时间y
)
在图形窗口中,我们应该会看到一个“跳跃”的点。从某个高度垂直向下,没有看到投影线/迹线。
这是我工作的一部分。我不知道在程序中引入t
的位置:
Tc
编辑:
这是整个计划。我应用并修改了@Mike Muller给出的建议,但它没有起作用。我不明白哪里出错了。希望你能澄清我的怀疑。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.empty(n) ; x.fill(1) # the vertical position is fixed on x-axis
y = 0.5*g*i^2 + h # the equation of diver's displacement on y axis
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.show()
答案 0 :(得分:0)
您需要使用生成器来生成y数据。这有效:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], ' o', lw=2)
g = 9.81
h = 2
tc = 200
xs = [1] # the vertical position is fixed on x-axis
ys = [h, h]
# animation function. This is called sequentially
def animate(y):
ys[-1] = y
line.set_data(xs, ys)
return line,
def get_y():
for step in range(tc):
t = step / 100.0
y = -0.5*g*t**2 + h # the equation of diver's displacement on y axis
yield y
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100)
plt.show()
这应该有效:
# -*- coding: utf-8 -*-
from math import *
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
def Plongeon():
h = float(input("height = "))
g = 9.81
#calculate air time, Tc
Tc = sqrt(2 * h / g)
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, h+1)) #ymax : initial height+1
line, = ax.plot([], [], ' o', lw=2)
step = 0.01 # animation step
xs = [1] # the vertical position is fixed on x-axis
ys = [h]
# animation function. This is called sequentially
def animate(y):
ys[-1] = y
line.set_data(xs, ys)
return line,
def get_y():
t = 0
while t <= Tc:
y = -0.5 * g * t**2 + h # the equation of diver's displacement on y axis
yield y
t += step
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100)
plt.show()
Plongeon()
我删除了不需要的行。无需global
。此外,程序中的任何地方都没有使用质量。
这是最重要的部分:
def get_y():
t = 0
while t <= Tc:
y = -0.5 * g * t**2 + h
yield y
t += step
你需要增加一点时间。