animate with variable time

泄露秘密 提交于 2019-12-20 06:15:12

问题


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:


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:



来源:https://stackoverflow.com/questions/49796314/animate-with-variable-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!