1

I have trajectory data where each vehicle has its own time to start. Each vehicle is a point in the animation. So, in the dataset, for each row there is coordinate point (x,y) along with a timestamp. So, fixed time interval would not work for me. I tried with loop and sleep but it not showing the animation but only the first result. But if debug line by line, it seems okay(updating with new points after each iteration). Here is my code (this is to test: loop, sleep and animation):

    #sample data
    x=[20,23,25,27,29,31]
    y=[10,12,14,16,17,19]
    t=[2,5,1,4,3,1,]
    #code
    fig, ax = plt.subplots()
    ax.set(xlim=(10, 90), ylim=(0, 60))  
    for i in range(1,6):
        ax.scatter(x[:i+1], y[:i+1])
        plt.show()
        time.sleep(t[i])

How can get the animation effect?

1
  • I am not sure what you are saying. Could you please explain a little. Thanks Commented Apr 12, 2018 at 12:35

1 Answer 1

3

The already mentioned FuncAnimation has a parameter frame that the animation function can use an index:

import matplotlib.pyplot as plt
import matplotlib.animation as anim

fig = plt.figure()

x=[20,23,25,27,29,31]
y=[10,12,14,16,17,19]
t=[2,9,1,4,3,9]

#create index list for frames, i.e. how many cycles each frame will be displayed
frame_t = []
for i, item in enumerate(t):
    frame_t.extend([i] * item)

def init():
    fig.clear()

#animation function
def animate(i): 
    #prevent autoscaling of figure
    plt.xlim(15, 35)
    plt.ylim( 5, 25)
    #set new point
    plt.scatter(x[i], y[i], c = "b")

#animate scatter plot
ani = anim.FuncAnimation(fig, animate, init_func = init, 
                         frames = frame_t, interval = 100, repeat = True)
plt.show()

Equivalently, you could store the same frame several time in the ArtistAnimation list. Basically the flipbook approach.

Sample output: enter image description here

3
  • Thanks. I am not sure but what I understand that, for example, for 20 second you are creating 20 cycles and the frame will be shown for 20 cycles. In the output, the time interval is not equal to 20 seconds. So, my questions are, did I understand right? if so, how much time for each cycle? Thanks again Commented Apr 12, 2018 at 15:19
  • The frame list gives just a relative measure, how long each frame is visible in comparison to the others. The parameter interval determines the delay between frames in ms. So if your time list contains a value in seconds, then you can set interval to 1000 ms = 1 s. If your time list would be in ms, you set the parameter to 1.
    – Mr. T
    Commented Apr 12, 2018 at 15:45
  • Thanks you very much, now I understand. Commented Apr 12, 2018 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.