2017-11-25 129 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

相關問題