-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()
後來我想添加在劇情中生成多個隨機遊走的可能性(我的意思是我希望他們同時生成)。我該怎麼做?
不幸的是:( – Hendrra
)如果你沒有看到一個動畫,如果你糾正了代碼本身,那是因爲你沒有對動畫的引用,讓你的函數返回動畫,當在IPython中運行時,你不一定需要'plt.show()'。 – ImportanceOfBeingErnest