Matplotlib动画多行和文本

时间:2013-12-17 01:38:36

标签: python animation matplotlib

感谢您花时间阅读我的问题,我第一次发布SO所以这里就是......

我正在使用matplotlib.animation.FuncAnimation

在动画中绘制时间序列数据

我通过循环遍历列表并从numpy数组中切片数据来绘制多行。 这样可以正常工作,但我还想在动画中添加文本并描述帧编号。

我在下面提供了示例代码。

我正在尝试从animate函数返回一个行对象列表一个文本对象。 我尝试这样做时收到属性错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 531, in callit
    func(*args)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 141, in _on_timer
    TimerBase._on_timer(self)
  File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1117, in _on_timer
    ret = func(*args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 773, in _step
    still_going = Animation._step(self, *args)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 632, in _step
    self._draw_next_frame(framedata, self._blit)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 652, in _draw_next_frame
    self._post_draw(framedata, blit)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 675, in _post_draw
    self._blit_draw(self._drawn_artists, self._blit_cache)
  File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 688, in _blit_draw
    if a.axes not in bg_cache:
AttributeError: 'list' object has no attribute 'axes'

但是,假设我有两个行对象的列表,如果我单独返回对象,例如

return lines[0],lines[1], timetext

我没有收到错误。

有什么想法吗?

干杯 蛱蝶

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

npdata = numpy.random.randint(100, size=(5,6,10))
plotlays, plotcols = [2,5], ["black","red"]

fig = plt.figure()
ax = plt.axes(xlim=(0, numpy.shape(npdata)[0]), ylim=(0, numpy.max(npdata)))
timetext = ax.text(0.5,50,'')

lines = []
for index,lay in enumerate(plotlays):
    lobj = ax.plot([],[],lw=2,color=plotcols[index])[0]
    lines.append(lobj)

def init():
    for line in lines:
        line.set_data([],[])
    return lines

def animate(i):
    timetext.set_text(i)
    x = numpy.array(range(1,npdata.shape[0]+1))
    for lnum,line in enumerate(lines):
        line.set_data(x,npdata[:,plotlays[lnum]-1,i])
    return lines, timetext

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=numpy.shape(npdata)[1], interval=100, blit=True)

plt.show()

1 个答案:

答案 0 :(得分:6)

def animate(i):
    timetext.set_text(i)
    x = numpy.array(range(1,npdata.shape[0]+1))
    for lnum,line in enumerate(lines):
        line.set_data(x,npdata[:,plotlays[lnum]-1,i])
    return lines, timetext # <- returns a tuple of form (list, artist)

将此更改为

     return tuple(lines) + (timetext,)

或类似内容,以便您从animate返回一个可迭代的艺术家。