2015-08-14 127 views
2

我想模擬使用Matplotlib的圓和動畫從選定的數據點的圓形激波的動畫。 但我無法想出一種方法來刪除每個新框架中的舊圈子。其結果是,隨着半徑增大,我得到了越來越多的圈在畫布上繪製 - 這樣的:matplotlib圈,動畫,如何刪除動畫中的舊圓

enter image description here

上一個matplotlib劇情動畫圓形的衝擊波有什麼建議?

我到目前爲止的代碼是:

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

testData = np.random.rand(100,2)-[0.5, 0.5] 

fig, ax = plt.subplots() 
def init(): 
    fig.clf() 
    sctPlot, = ax.plot(testData[:,0], testData[:,1], ".") 

# i is the radius 
def animate(i): 
    init() 
    q = 20 #initial index for the starting position 
    pos = testData[q,:] 
    circle1=plt.Circle(pos,i,color='r',fill=False, clip_on = False) 
    fig.gca().add_artist(circle1) 

def init(): 
    sctPlot, = ax.plot(testData[:,0], testData[:,1], ".") 
    return sctPlot, 

ani = animation.FuncAnimation(fig, animate, np.arange(0.4, 2, 0.1), init_func=init, 
    interval=25, blit=False) 
plt.show() 

回答

3

我想你可以只使用set_radius每次改變圓圈大小:

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


testData = np.random.rand(100,2)-[0.5, 0.5] 

fig, ax = plt.subplots() 
circle1=plt.Circle(testData[20,:],0,color='r',fill=False, clip_on = False) 
ax.add_artist(circle1) 
# i is the radius 
def animate(i): 
    #init() 
    #you don't want to redraw the same dots over and over again, do you? 
    circle1.set_radius(i) 


def init(): 
    sctPlot, = ax.plot(testData[:,0], testData[:,1], ".") 
    return sctPlot, 

ani = animation.FuncAnimation(fig, animate, np.arange(0.4, 2, 0.1), init_func=init, 
    interval=25, blit=False) 
plt.show() 

所以你不刪除,重劃補丁每一輪,我想這可能是更有效的。

+0

謝謝... set_radius正是我所需要的。非常感激。 –

+0

嗨,再次。新代碼工作正常,但不在ipython筆記本上。它似乎崩潰了內核。我用%pylab tk彈出了plt窗口。你認爲這與此有關嗎? –

+0

可能是傳統知識問題?如果你不在ipython筆記本上,它有效嗎?我使用OSX後端,根本沒有得到這個問題。 –

1

將此代碼添加到您的動畫功能:

for obj in ax.findobj(match = type(plt.Circle(1, 1))): 
    obj.remove() 

ax.findobj(match = type(plt.Circle(1, 1)))查找軸線上的所有圓圈的補丁,然後你就可以刪除然後繪製一個新的圈子。我使用plt.Circle()來創建一個圓形對象來匹配 - 通過它的參數並不重要。