2015-10-18 44 views
4

我想通過動畫在for循環中繪製一些數據。我希望它等到動畫完成,然後繼續進行for循環。暫停似乎工作,讓這個,但有時電影很長,我想關閉,並轉移到下一個。有人知道我能做到嗎?for循環中的Matplotlib動畫?

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
import time 

for j in range(0,2): 
fig = plt.figure(j) 
mngr = plt.get_current_fig_manager() 
mngr.window.setGeometry(j*256,0,256, 256) 

ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 
line, = ax.plot([], [], lw=2) 

# initialization function: plot the background of each frame 
def init(): 
    line.set_data([], []) 
    return line, 

# animation function. This is called sequentially 
def animate(i): 
    x = np.linspace(0, 2, 1000) 
    y = np.sin(2 * np.pi * (x - 0.01 * i+j/4.)) 
    line.set_data(x, y) 
    return line, 

# call the animator. blit=True means only re-draw the parts that have changed. 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
           frames=200, interval=20, blit=True,repeat=False) 

plt.pause(0.02*200) 

plt.show(block=True) 
+0

在'plt.pause(0.02 * 200)'後面加上'plt.close()'' –

回答

0

一種方法是使用KeyboardInterrupt異常移動到下一個圖。 爲了更好的可讀性,將您繪製成一個函數:現在

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
import time 



def animate_multi(j): 
    fig = plt.figure(j) 
    mngr = plt.get_current_fig_manager() 
    mngr.window.setGeometry(j*256,0,256, 256) 

    ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 
    line, = ax.plot([], [], lw=2) 

    # initialization function: plot the background of each frame 
    def init(): 
     line.set_data([], []) 
     return line, 

    # animation function. This is called sequentially 
    def animate(i): 
     x = np.linspace(0, 2, 1000) 
     y = np.sin(2 * np.pi * (x - 0.01 * i+j/4.)) 
     line.set_data(x, y) 
     return line, 

    # call the animator. blit=True means only re-draw the parts that have changed. 
    anim = animation.FuncAnimation(fig, animate, init_func=init, 
           frames=200, interval=20, blit=True,repeat=False) 

    plt.pause(0.02*200) 
    plt.close() 
    plt.show(block=True) 

,在循環除了KeyboardInterrup,並繼續到下一個動畫:

for j in range(5): 
    try: 
     print('Working on plot', j) 
     animate_multi(j) 
    except KeyboardInterrupt: 
     plt.close() 

注:您可能必須按<Ctrl>-<C>兩次跳到下一個動畫。

+0

這是否適合您? –