Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to animate a discontinuous line in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading