2017-11-25 135 views
-1

我正在用Python编码随机游走我的第二维。我想动画如何“增长”。我想使用matplotlib中的animation.FuncAnimation,但不幸的是,它不起作用,因为我想。没有错误,但我在iPython控制台中使用了%matplotlib tk
我的代码:虽然没有错误,但不起作用的动画[Python]

def random_walk_animated_2D(n, how_many = 1): 

    possible_jumps = np.array([[0, 1], [1, 0], [-1, 0], [0, -1]]) 
    where_to_go = np.random.randint(4, size = n) 
    temp = possible_jumps[where_to_go, :] 
    x = np.array([[0, 0]]) 
    temp1 = np.concatenate((x, temp), axis = 0) 
    trajectory = np.cumsum(temp1, axis = 0) 

    fig = plt.figure() 
    ax = plt.axes(xlim = (np.amin(trajectory, axis = 0)[0], np.amax(trajectory, axis = 0)[0]), 
        ylim = (np.amin(trajectory, axis = 0)[1], np.amax(trajectory, axis = 0)[1])) 
    line, = ax.plot([], [], lw = 2) 

    def init(): 
     line.set_data([], []) 
     return line, 

    def animate(i): 
     line.set_data(trajectory[i, 0], trajectory[i, 1]) 
     return line, 

    anim = animation.FuncAnimation(fig, animate, init_func = init, 
            frames = 200, interval = 30, blit = True) 
    plt.show() 

遗憾的是没有运行的功能后会发生。 Screenshot of the plot

后来我想添加在剧情中生成多个随机游走的可能性(我的意思是我希望他们同时生成)。我该怎么做?

回答

0

不可能通过一个点画一条线。
如果要绘制直线图,则参数plot或直线的set_data方法必须至少有两个点。

而不是line.set_data(trajectory[i, 0], trajectory[i, 1])你可能想

line.set_data(trajectory[:i, 0], trajectory[:i, 1]) 

密谋通过所有点排队到i个点。

+0

不幸的是:( – Hendrra

+0

)如果你没有看到一个动画,如果你纠正了代码本身,那是因为你没有对动画的引用,让你的函数返回动画,当在IPython中运行时,你不一定需要'plt.show()'。 – ImportanceOfBeingErnest

相关问题