使用matplotlib.animation创建动画并保存动画时,试图通过plt.close关闭图形窗口时会出现错误。
Python版本:
Python2.7.12\Anaconda自定义(64位)\x{e76f}(缺省值,2016年7月2日,17:42:40)
IPython 4.1.2 --一个增强的交互式Python
目前,我切换到使用PyCharm 2017.1社区版。当从IPython或%paste
运行IPython或在PyCharm的交互控制台使用Shift+Alt+E运行时,错误信息可以直接在%cpaste
或%paste
中再现,也可以在%paste
中直接再现。使用的电影编码器是mplayer中集成的菜单编码器,因为这是在我的工作地点安装的默认编码器。
注意:
plt.ion()
打开交互模式(默认情况下已在PyCharm中打开)%paste
)除plt.close()
以外的所有命令,然后手动键入plt.close()
时,代码都会在plt.close()
或PyCharm中无错误地退出。plt.close()
替换plt.clf()
时,代码没有出错,但是我需要plt.close()
,例如在循环中创建动画,在循环中需要从头开始重新创建图形。time.sleep(1)
时,代码退出带有错误的time.sleep(1)
,因此该问题很可能与代码中的时间冲突无关。下面给出了一个最小、完整和(希望)可验证的示例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# animation function for random image data
def animate_random_data(i):
new_data = np.random.rand(10, 10)
# update the data
im.set_data(new_data)
# initialize the graph
first_data = np.random.rand(10,10)
im = plt.imshow(first_data,interpolation='none')
myfig = plt.gcf()
# create the animation and save it
ani = animation.FuncAnimation(myfig, animate_random_data, range(10),
interval=100)
ani.save('animation_random_data.mpg', writer='mencoder')
plt.close()
错误跟踪(来自PyCharm):
Traceback (most recent call last):
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 176, in __draw_idle_agg
FigureCanvasAgg.draw(self)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 474, in draw
self.figure.draw(self.renderer)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/figure.py", line 1165, in draw
self.canvas.draw_event(renderer)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1809, in draw_event
self.callbacks.process(s, event)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/cbook.py", line 563, in process
proxy(*args, **kwargs)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/cbook.py", line 430, in __call__
return mtd(*args, **kwargs)
File "/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib/animation.py", line 652, in _start
self.event_source.add_callback(self._step)
AttributeError: 'NoneType' object has no attribute 'add_callback'
尽管程序在手动关闭窗口时没有出现错误,如上面列表中所写,但它是一个恼人的错误(请考虑一个循环中的多个动画)。例如,一维线图也会出现错误。感谢您的帮助(并澄清此错误信息的确切含义)!
发布于 2017-05-04 07:55:51
此错误来自关闭图形时仍在运行的动画。虽然在大多数情况下,关闭图形时会自动停止动画,但在交互模式下,情况似乎并非如此。
一个解决方案可以是明确地停止动画并在关闭图形之前删除它。
ani = animation.FuncAnimation(...)
ani.save(...)
ani.event_source.stop()
del ani
plt.close()
https://stackoverflow.com/questions/43776528
复制相似问题