用可变的时间动画 [英] animate with variable time

查看:35
本文介绍了用可变的时间动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有轨迹数据,每辆车都有自己的启动时间.每辆车都是动画中的一个点.因此,在数据集中,每行都有一个坐标点(x,y)以及一个时间戳.因此,固定的时间间隔对我不起作用.我尝试使用 loopsleep 但它没有显示动画而只显示第一个结果.但是如果逐行调试,似乎没问题(每次迭代后更新新点).这是我的代码(这是为了测试:loopsleepanimation):

 #示例数据x=[20,23,25,27,29,31]y = [10,12,14,16,17,19]t = [2,5,1,4,3,1,]#代码无花果,ax = plt.subplots()ax.set(xlim =(10,90),ylim =(0,60))对于范围内的 i (1,6):ax.scatter(x[:i+1], y[:i+1])plt.show()时间.sleep(t[i])

如何获得动画效果?

解决方案

已经提到的

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?

解决方案

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:

这篇关于用可变的时间动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆