我正在尝试使用FuncAnimation和circle.set_radius()制作一个扩大的圆圈的动画。但是,动画仅在blit = False时起作用。代码如下:

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

fig, ax = plt.subplots()
plt.grid(True)
plt.axis([-0.6, 0.6, -0.6, 0.6])
circle1= plt.Circle([0,0],0.01,color="0.",fill=False, clip_on = True)
ax.add_patch(circle1)

dt = 1.0/20
vel = 0.1

def init():
    circle1.set_radius(0.01)

def animate(i):
    global dt, vel
    r = vel * i * dt
    circle1.set_radius(r)
    return circle1,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval= 50, blit=True)


它返回此错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1139, in draw
    self.canvas.draw_event(renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1809, in draw_event
    self.callbacks.process(s, event)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py", line 562, in process
    proxy(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py", line 429, in __call__
    return mtd(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/animation.py", line 620, in _start
    self._init_draw()
  File "/usr/local/lib/python2.7/site-packages/matplotlib/animation.py", line 1166, in _init_draw
    for a in self._drawn_artists:
TypeError: 'NoneType' object is not utterable


我正在使用Mac OS。当我更改blit = False时,动画将起作用。但是,每当我移动鼠标时,动画就会变慢。这是有问题的,因为我有一个单独的线程来生成声音输出。实际上,圆会撞到一些数据点并发出声音。结果,它们不同步。请帮忙。

最佳答案

From the docs


  如果blit = True,则func和init_func应该返回可迭代的drawable清除。


因此-您需要将return circle1,添加到函数init()中。另一个选择是在调用init_func时完全不指定FuncAnimation-您可能不需要它。如果没有动画,动画可能会做您想要的。

注意circle1之后的尾部逗号-这意味着将返回一个(1个元素)元组,以便返回值可以根据需要进行迭代。您已经在animate函数中具有此功能。

关于python - Matplotlib FuncAnimation,当blit = true时出错。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35068396/

10-09 05:06