Matplotlib动画,文字不更新

3

我是Matplotlib动画的新手,遇到了一些问题。我想创建一个粒子位置的动画,并在每个步骤显示帧数。我在代码片段的开头创建了示例数据,因此代码是自包含的(通常我的数据是从CSV文件中读取的)。

问题在于-显示的图表完全空白。但是,如果我注释掉time_text的返回(即将“return patches,time_text”更改为“return patches”),则一切正常。我认为问题在于我如何更新time_text,但我卡住了该如何解决它的方法。


from matplotlib import pyplot as plt  
from matplotlib import animation  
import numpy as np  
import pandas as pd  

box_size = 50  
radius = 1

df =pd.DataFrame(np.array([np.arange(50),np.arange(50),np.arange(50)]).T,
                          columns = ['x','y','frame'])

#set up the figure
fig = plt.figure()
plt.axis([0,box_size,0,box_size])
ax = plt.gca()
ax.set_aspect(1)
time_text = ax.text(5, 5,'')

#initialization of animation, plot empty array of patches
def init():
    time_text.set_text('initial')
    return []

def animate(i):
    patches = []
    #data for this frame only
    data = df[df.frame == i]
    time_text.set_text('frame'+str(i))
    #plot circles at particle positions
    for idx,row in data.iterrows():
        patches.append(ax.add_patch(plt.Circle((row.x,row.y),radius,color= 'b',
                                               alpha = 0.5)))            
    return patches, time_text

anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = False,
                               frames=int(df.frame.max()), interval=50, 
                                blit=True)

可能这个问题会有所帮助。 - ImportanceOfBeingErnest
1个回答

0

你需要让你的初始化函数返回pyplot.text对象。你还应该在每次从anim函数调用时初始化你想要修改的对象。

看一下ArtistAnimation,它可能更适合你正在做的事情。

为了避免许多圆圈聚集在画布上,我宁愿更新路径对象的位置,而不是在每次迭代时附加新的路径对象。

from matplotlib import pyplot as plt  
import matplotlib.patches as patches
from matplotlib import animation  
import numpy as np  
import pandas as pd  

box_size = 50  
radius = 1

df = pd.DataFrame(np.array([np.arange(50),np.arange(50),np.arange(50)]).T,
                          columns = ['x','y','frame'])

#set up the figure
fig = plt.figure()
plt.axis([0,box_size,0,box_size])
ax = plt.gca()
time_text = ax.text(5, 5,'')

circle = plt.Circle((1.0,1.0), radius,color='b', alpha=0.5, facecolor='orange', lw=2)


#initialization of animation, plot empty array of patches
def init():
    time_text.set_text('initial')
    ax.add_patch( circle )
    return time_text, ax

def animate(i):
    #data for this frame only
    data = df[df.frame == i]
    time_text.set_text('frame' + str(i) )

    #plot circles at particle positions
    for idx,row in data.iterrows():
        circle.center = row.x,row.y

    return time_text, ax

anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = False,
                               frames=int(df.frame.max()), interval=200, blit=True)

plt.show()

@mdriscoll 欢迎来到 Stack Overflow。请注意,我的解决方案引入了一个问题,您需要找到一种方法在添加新路径时删除旧路径。 - snake_charmer
很遗憾,让init()函数返回time_text并不能解决问题——它仍然返回一个空的图形,没有动画。我是否错过了FuncAnimation中的某个参数? - mdriscoll
它应该返回至少2个对象,因为该方法需要一个可迭代的对象。这就是为什么我返回了matplotlib.axes.AxesSubplot。我发布的修改后的代码显示了一个动画,在我的两台计算机上都有一个变化的文本,你试过运行它吗? - snake_charmer
谢谢 - 你发布的代码确实更新了文本。然而,现在补丁只是附加到同一个ax对象上,所以我看到所有的圆圈,而不是一个移动的圆圈。有没有一种方法可以清除ax对象?(这就是为什么我在原始代码的animate函数中有patches = []这一行的原因) - mdriscoll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接