为每一步绘制一个点 i

lugia54

我正在做一个自由落体计算(真的很简单),并想绘制对象高度的每个实例——即当它“下落”时要显示的对象的高度。我尝试通过 for 循环运行它,但我只是绘制了最终结果。对于每个人,我需要做些什么来显示物体掉落时 - 而不仅仅是最终结果。这是我的代码:

#Input parameters
y1 = 490 #starting position
y2 = 0 #ground
g = -9.81   #gravity
VY = 0 #starting speed

import math
import numpy as np
import matplotlib.pyplot as plt

sqrt_part = math.sqrt(VY**2-2*g*(y1-y2))
t1 = - VY - sqrt_part/g
t2 = - VY + sqrt_part/g

if t1 > 0:
    t = t1
else:
    t = t2      
print('t = '  + str(t) + ' ' + 's')    

t_space = np.linspace(0,t,50)
y_t = y1 + VY * t_space + 0.5 * g * t_space**2
v_t = abs(y_t[1:] - y_t[0:-1])/abs(t_space[0:-1] - t_space[1:])

plt.plot(t_space, y_t, 'go')
plt.plot(t_space[1:], v_t, 'r--')

for i in range(np.size(t_space)):
    plt.plot(t_space[i], y_t[i], 'go')

for 循环显示与它上面的图相同,但我希望它在移动时更新并显示“ro”。我该怎么做?左边是我得到的,右边是我想要的在此处输入图像描述

Davide_sd

请看一下matplotlib 动画 api

#Input parameters
y1 = 490 #starting position
y2 = 0 #ground
g = -9.81   #gravity
VY = 0 #starting speed

import math
import numpy as np
import matplotlib.pyplot as plt

sqrt_part = math.sqrt(VY**2-2*g*(y1-y2))
t1 = - VY - sqrt_part/g
t2 = - VY + sqrt_part/g

if t1 > 0:
    t = t1
else:
    t = t2   

print('t = '  + str(t) + ' ' + 's')    

t_space = np.linspace(0,t,50)
y_t = y1 + VY * t_space + 0.5 * g * t_space**2
v_t = np.abs((np.roll(y_t, -1) - y_t) / (np.roll(t_space, -1) - t_space))
v_t = np.roll(v_t, 1)
v_t[0] = 0

from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
# create two empty lines
ln_y, = plt.plot([], [], 'go', label="y")
ln_v, = plt.plot([], [], 'r--', label="v")

def init():
    ax.set_xlim(0, max(t_space))
    ax.set_ylim(0, max(y_t))
    ax.set_xlabel("t")
    ax.legend()
    return ln_y, ln_v

def update(i):
    # i represents the index of the slice to use at the current frame
    ln_y.set_data(t_space[:i], y_t[:i])
    ln_v.set_data(t_space[:i], v_t[:i])
    return ln_y, ln_v,

ani = FuncAnimation(fig, update, frames=range(len(v_t)),
                    init_func=init, blit=False, repeat=False)
plt.show()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章