【发布时间】:2017-01-05 09:48:22
【问题描述】:
我创建了一些效果很好的动画——尽管在设置关键字时很慢:
blit=False
但是,在我通过设置 blit=True 来加快动画速度的过程中,我在运行测试时遇到了一些奇怪的 KeyError 异常。
最后,我有一种预感,这可能与编码错误无关,但可能与设置甚至错误有关。
于是我从here导入了simple_anim.py脚本,发现也出现了同样的错误。
我测试了更多示例,它们都给出了相同的例外.... :(
任何人都可以帮助我并提供一些关于发生了什么的信息吗?
代码如下:
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,
# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
引发的异常是:
Traceback (most recent call last):
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/backend_bases.py", line 1305, in _on_timer
ret = func(*args, **kwargs)
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/animation.py", line 1021, in _step
still_going = Animation._step(self, *args)
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/animation.py", line 827, in _step
self._draw_next_frame(framedata, self._blit)
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/animation.py", line 845, in _draw_next_frame
self._pre_draw(framedata, blit)
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/animation.py", line 858, in _pre_draw
self._blit_clear(self._drawn_artists, self._blit_cache)
File "/home/dj754/anaconda3/lib/python3.5/site-packages/matplotlib/animation.py", line 898, in _blit_clear
a.figure.canvas.restore_region(bg_cache[a])
KeyError: <matplotlib.axes._subplots.AxesSubplot object at 0x7fb3b9d3a198>
【问题讨论】:
-
我只在
interval低于60时遇到了这个问题 - 我的错误表明问题从用于显示窗口的Tkinter开始。可能程序启动两个线程(或者更确切地说使用 Tkinterafter()定期执行animate()并且某些元素比第一个元素需要的其他元素启动得更快。 -
当我在家中运行此代码时 - 我认为是 - 相同的软件配置:一切正常。但是......当我在使用
FuncAnimation(....)调用创建动画之前插入plt.show()语句时,我已经能够重新创建相同的 KeyError 内容......我有一种感觉,我正在做某事。跨度> -
.. 经过进一步调查,我发现在代码开头添加
plt.ion()语句会导致它给出KeyError异常,仅当blit=True' was set. In when I changed this toblit=False' 它仍然有效。不幸的是,我无法在工作中测试我的代码(基于此我提出了这个问题),但我很快就会这样做。
标签: python python-3.x animation matplotlib blit