我正在使用matplotlib动画,调用方式如下:
plot = animation.FuncAnimation(fig, update, frames=data_gen(a), init_func=init, interval=10, blit=True)
这里,“a”是数据生成函数data_gen的初始值,它长这样:
data_gen(x)
old_x = x
while True:
new_x = func(old_x)
old_x = new_x
yield new_x
这段代码的意图是,当动态图形绘制更新时,data_gen会生成一个新值来替换new_x变量。
但是......实际上发生了这样的情况:
animation.py文件在FuncAnimation类的init()方法中出现了错误。
问题发生在以下代码中:
elif iterable(frames):
self._iter_gen = lambda: iter(frames)
self.save_count = len(frames)
错误为"TypeError: object of type 'generator' has no len()"。
看起来data_gen可迭代,但没有长度。
下面是FuncAnimation类中init()方法的更多代码:
# Set up a function that creates a new iterable when needed. If nothing
# is passed in for frames, just use itertools.count, which will just
# keep counting from 0. A callable passed in for frames is assumed to
# be a generator. An iterable will be used as is, and anything else
# will be treated as a number of frames.
if frames is None:
self._iter_gen = itertools.count
elif isinstance(frames, collections.Callable):
self._iter_gen = frames
elif iterable(frames):
self._iter_gen = lambda: iter(frames)
self.save_count = len(frames)
else:
self._iter_gen = lambda: iter(list(range(frames)))
self.save_count = frames
我不确定为什么我的data_gen不是collections.Callable。如果是这样的话,那么len(frames)就不会发生了。
如果您有任何关于我应该怎么做的建议,将不胜感激!