我正在做一個自由落體計算(真的很簡單),并想繪制物件高度的每個實體——即當它“下落”時要顯示的物件的高度。我嘗試通過 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”。我該怎么做?左邊是我得到的,右邊是我想要的 在此處輸入影像描述
uj5u.com熱心網友回復:
請看一下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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456881.html
