2013-05-24 29 views

cevap

25

Burada, fare tıklamaları üzerinde duraklatmak için değiştirdiğim a FuncAnimation example. Animasyon, pause genel değişkeni True olduğunda, bir jeneratör işlevi, simData tarafından çalıştırıldığı için, aynı verileri elde etmek, animasyonun duraklatılmasını sağlar.

paused değeri bir olay geri arama kurarak konum değiştirir:

def onClick(event): 
    global pause 
    pause ^= True 
fig.canvas.mpl_connect('button_press_event', onClick) 

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 

pause = False 
def simData(): 
    t_max = 10.0 
    dt = 0.05 
    x = 0.0 
    t = 0.0 
    while t < t_max: 
     if not pause: 
      x = np.sin(np.pi*t) 
      t = t + dt 
     yield x, t 

def onClick(event): 
    global pause 
    pause ^= True 

def simPoints(simData): 
    x, t = simData[0], simData[1] 
    time_text.set_text(time_template%(t)) 
    line.set_data(t, x) 
    return line, time_text 

fig = plt.figure() 
ax = fig.add_subplot(111) 
line, = ax.plot([], [], 'bo', ms=10) 
ax.set_ylim(-1, 1) 
ax.set_xlim(0, 10) 

time_template = 'Time = %.1f s' 
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) 
fig.canvas.mpl_connect('button_press_event', onClick) 
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10, 
    repeat=True) 
plt.show() 
+0

Mükemmel, çok teşekkürler! Bu benim için hile yaptı. –

+0

Sevimli, kullanışlı, eğlenceli ve bir şekilde, nostaljik; https://youtu.be/TxmZ5sabk7U?t=17 veya https://youtu.be/C1HuX6nQnQY?t=211 – uhoh

4

Bu çalışır ...

anim = animation.FuncAnimation(fig, animfunc[,..other args]) 

#pause 
anim.event_source.stop() 

#unpause 
anim.event_source.start() 
4

@fred cevaplar birleştirmek uzun @unutbu burada, animasyonu oluşturduktan sonra bir onClick işlevi ekleyebiliriz:

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

fig = plt.figure() 

def run_animation(): 
    anim_running = True 

    def onClick(event): 
     nonlocal anim_running 
     if anim_running: 
      anim.event_source.stop() 
      anim_running = False 
     else: 
      anim.event_source.start() 
      anim_running = True 

    def animFunc(...args...): 
     # Animation update function here 

    fig.canvas.mpl_connect('button_press_event', onClick) 

    anim = animation.FuncAnimation(fig, animFunc[,...other args]) 

run_animation() 

Artık animasyonu tıklamayla durdurabilir veya başlatabiliriz.

+0

Matplotlib'in hangi sürümünü kullanıyorsunuz? Bu benim için işe yaramıyor gibi görünüyor – bretcj7

+0

@ bretcj7 Sürüm 1.5.3 kullanıyorum. Üzgünüm, bundan bahsetmeliydin! – woodenflute

+2

Event_source.stop() için matplotlib belgesini bulamıyorum veya başlatılamıyor muyum? Var mı? – bretcj7