2013-05-24 122 views

答えて

25

ここではa FuncAnimation exampleをマウスクリックで一時停止するように変更しました。 アニメーションはジェネレータ関数simDataによって駆動されるため、グローバル変数pauseがTrueの場合、同じデータを生成するとアニメーションが一時停止したように見えます。

pausedの値は、イベントのコールバックを設定することで切り替えられる。

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

優秀、ありがとうございます!それが私のトリックでした。 –

+0

かわいい、便利な、面白い、そして方法では、ノスタルジックな; https://youtu.be/TxmZ5sabk7U?t=17またはhttps://youtu.be/C1HuX6nQnQY?t=211 – uhoh

4

これは動作します...

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

#pause 
anim.event_source.stop() 

#unpause 
anim.event_source.start() 
4

が@fredからの回答の両方を組み合わせると、 @unutbuここでは、アニメーションの作成後にonClick関数を追加できます:

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() 

ここで、クリックするだけでアニメーションを停止または開始することができます。

+0

実行しているmatplotlibのバージョンは?これは私にとってはうまくいかないようです – bretcj7

+0

@ bretcj7私はバージョン1.5.3を使用しています。申し訳ありませんが、それを述べたはずです! – woodenflute

+2

私はevent_source.stop()またはmatplotlibのドキュメントを見つけることができないのでしょうか?それは存在しますか? – bretcj7

関連する問題