【问题标题】:matplotlib animation, text not updatingmatplotlib 动画,文本不更新
【发布时间】:2015-03-13 07:33:57
【问题描述】:

我是使用 Matplotlib 制作动画的新手,遇到了一些麻烦。我想创建一个粒子位置的动画,我想在每一步显示帧号。我在代码 sn-p 的开头创建了示例数据,因此代码是独立的(通常我的数据是从 csv 读取的)。

问题 - 显示的绘图完全空白。但是,如果我注释掉 time_text 的返回(即将“返回补丁,time_text”更改为“返回补丁”)一切正常。我认为问题在于我如何更新 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)

【问题讨论】:

标签: python-2.7 matplotlib


【解决方案1】:

您需要让您的初始化函数返回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。请注意,我的解决方案引入了一个问题,您必须找到一种方法在添加新路径时删除旧路径。
  • 不幸的是,让 init() 函数返回 time_text 并没有帮助 - 它仍然返回一个没有动画的空白图。我缺少 FuncAnimation 中的 kwarg 吗?
  • 它应该返回至少 2 个对象,因为该方法需要一个可迭代对象。这就是我返回matplotlib.axes.AxesSubplot 的原因。我发布的修改后的代码在我的两台电脑上都显示了一个带有变化文本的动画,你试过运行它吗?
  • 谢谢 - 您发布的代码确实更新了文本。然而,现在补丁只是被附加到同一个 ax 对象上,所以我看到了所有的圆圈,而不是一个移动的圆圈。有没有办法清除斧头对象? (这就是为什么我在原始代码的 animate 函数中有行 patch = [])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2022-12-09
  • 1970-01-01
  • 2021-02-13
  • 2014-06-07
  • 2014-01-04
  • 2023-03-13
相关资源
最近更新 更多