如何在matplotlib中为文字艺术家设置运动动画?

时间:2019-07-16 02:58:56

标签: python python-2.7 matplotlib animation

我正在尝试制作matplotlib中的一段文本动画,以便制作一些教学视频。但是,我无法设置动态文本。

我尝试使用FuncAnimation(就像我制作动画线一样),并将该文本的锚点定义为一对移动坐标。这是我尝试过的:

def data_gen(): #Data generator. Gives me the anchor.
    counter = 0
    x0 = data_gen.x0
    while counter < 1000:
        counter+=1
        x0-=0.09
        yield x0,(1-counter*0.05)
data_gen.x0=1

def animate_text(data): #Here is where I try to tell my code to refresh 
#only the coordinates of the text.
    x0,y0 = data
    text_sample = ax.text(x0,y0,'text here',transform=ax.transAxes, 
fontsize=12, color='black',fontstyle='oblique',family='serif')
    return text_sample

#animation part:

ani = animation.FuncAnimation(fig,animate_text,data_gen,blit=True,
interval=50,repeat = False)
plt.show()

但是,我得到了:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 387, 
in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 227, 
in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1026, in 
_start
self._init_draw()
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1750, in 
_init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1777, in 
_draw_frame
for a in self._drawn_artists:
TypeError: 'Text' object is not iterable
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 387, 
in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 227, 
in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1308, in 
_handle_resize
self._init_draw()
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1750, in 
_init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1777, in 
_draw_frame
for a in self._drawn_artists:
TypeError: 'Text' object is not iterable

有人知道我该怎么解决吗?

1 个答案:

答案 0 :(得分:0)

FuncAnimation文档中,您可以阅读:

  

func必须返回所有已修改或   已创建

"iterable"意味着animate_text()必须返回包含元素的列表或元组-即使您只有一个元素:

return (text_sample,)