Matplotlib FuncAnimation, error when blit = true.

喜夏-厌秋 提交于 2021-02-11 04:32:56

问题


I am trying to make an animation of an expanding circle using FuncAnimation and circle.set_radius(). However, the animation only works when blit = False. The code is as follow:

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)

It returns this error:

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

I am using mac OS. The animation will work when I changed blit = False. However, whenever I move my mouse there animation slow down. This is problematic because I have a separate thread generating the sound output. In practice, the circle will hit some data points and make sound. As a result they are not in sync. Please help.


回答1:


From the docs,

If blit=True, func and init_func should return an iterable of drawables to clear.

Therefore - you need to add return circle1, to your function init(). The other option is not to specify an init_func at all in your call to FuncAnimation - you may not need it. The animations probably does what you want without it.

NOTE the trailing comma after circle1 - this means a (1 element) tuple is returned, so that the return value is iterable as required. You already have this in the animate function.



来源:https://stackoverflow.com/questions/35068396/matplotlib-funcanimation-error-when-blit-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!