Search code examples
pythonanimationnumpymatplotlibreal-time

Plot one real time graph after another


A diver jumps vertically down into water.

I want to plot the movement of a diver before diving into the water (from t=0 to t=Tc, Tc the the moment he touches the water) with his position both axes depend on time, follow by his movement after plunging into water (t > Tc)

I managed to plot the real time graph depicting his movement before plunging into water but how to add / replace with another equation after the moment he enters the water?

By the way, how to trace the water level , which is a fixed horizontal line at y=0 ?

Here is my code:

# -*- coding: utf-8 -*-
from math import * 
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation


print ("Height of diver (m) and weight of diver (kg)")
h = float(input(" height = "))

m = float(input(" mass = "))
g = 9.81                    #gravity = 10 m/s^2

Tc = sqrt(2*h/g)    #Tc = the time the diver touches water
Tc = round(Tc,2)    

Ve = g*Tc            #Ve = His initial velocity before plunging into water
Ve = round (Ve,2)


## movement in the water
#calculation of velocity's limit
dh = 0.9   #bouyancy, dh=0.9
k = 250    #coefficient of friction , k =250 kg/s
rate = m/k  
Vlim = rate*g*(1-(1/dh))  

# 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=(-30, h+1))  #ymax : initial height+1
line, = ax.plot([], [], ' o', lw=2)

step = 0.1  # 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

    while t > Tc:
        y = rate*Ve*(exp(-Tc/rate)-exp(-t/rate)) + rate*(abs(Vlim))*(exp(-Tc/rate)-exp(-t/rate)) + (abs(Vlim))*(Tc-t) # equation of diver's displacement in water on y axis
        yield y
        t += step # Indentation Error fixed

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

Solution

  • Now the code is working. I tested substituting

    y = -(t - Tc)
    

    instead of

    y = rate*Ve*(exp(-Tc/rate)-exp(-t/rate)) + rate*(abs(Vlim))*(exp(-Tc/rate)-exp(-t/rate)) + (abs(Vlim))*(Tc-t)
    

    and the particle moves with constant velocity. So it seems that your diver's displacement in water implementation has something wrong.