Using Python 3.12, Matplotlib 3.9.2
I’m trying to animate the change of the velocity of object B, which will be 0 after some time. However, the velocity jumped from the its minimum value to 0, and created an unwanted connecting line in between.
Is there any way to delete that line in my animation?
Here is the code that I used:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
t = np.linspace(0, 2, 100)
v = -10*t
v = np.where(v <= -10, 0, v)
fig = plt.figure()
plt.axis([0, 3, -12, 12])
av, = plt.plot([],[])
def animate(frame):
av.set_data(t[:frame],v[:frame])
return av,
ani = FuncAnimation(fig, animate, frames=len(t))
plt.show()
>Solution :
Define a threshold for identifying large steps. (or some other metric)
delta_v_threshold = 5
Calculate the difference between consecutive velocity values:
delta_v = np.abs(np.diff(v))
Then identify the steps that are ‘jumps’
large_step_indices = np.where(delta_v > delta_v_threshold)[0] + 1
Insert NaN/ replace with Nan to create discontinuity and avoid line drawing:
v_discontinuous = v.copy()
v_discontinuous[large_step_indices] = np.nan