Home > OS >  Ploting a point for each step i
Ploting a point for each step i

Time:04-04

I'm doing a free fall caluculations (really simple) and would like to plot each instance of height of the objects - that is the height of the object to be displayed as it 'falls' down. I tried running it throught a for loop, but i just get the end result plotted. What would i need to do to dislplay the object as it falls, for each individual - not just the end result. Here is my code:

#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')

The for loop displays the same as the plot above it, but i would like it to update and show the 'ro' as it moves thorught time. How would i do that? On the left is what i get, on the right is what i want enter image description here

CodePudding user response:

Please, take a look at matplotlib animation 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()
  • Related