【问题标题】:How to animate movement to a text artist in matplotlib?如何在 matplotlib 中为文本艺术家制作动画?
【发布时间】:2019-11-24 17:31:19
【问题描述】:

我正在尝试在 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

有人知道我该如何解决吗?

【问题讨论】:

  • 在您可以阅读的文档中:" func 必须返回所有已修改或创建的艺术家的可迭代对象"。这意味着animate_text() 必须返回带有元素的列表或元组——即使你只有一个元素——return (text_sample,)
  • @furas 好的!我正在编辑以显示完整的错误消息
  • 首先尝试return (text_sample,),如果您遇到新错误,请在说明中添加相关问题。

标签: python python-2.7 matplotlib animation


【解决方案1】:

FuncAnimation 文档中您可以阅读:

func 必须返回所有被修改的艺术家的可迭代对象或 已创建

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

return (text_sample,)

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 2018-05-05
    • 2012-07-10
    • 2017-05-24
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    相关资源
    最近更新 更多