使用matplotlib.animation创建动画并保存时,尝试通过plt.close关闭图形窗口时会出现错误:
Python版本:
Python 2.7.12 | Anaconda custom(64位)| (默认,2016年7月2日,17:42:40)
IPython 4.1.2 - 增强的交互式Python
目前我转而使用PyCharm 2017.1社区版。当从IPython中的%cpaste
或%paste
运行或使用Shift + Alt + E在PyCharm的交互式控制台中运行时,可以直接在IPython和PyCharm中重现错误消息。使用的电影编码器是集成在mplayer中的mencoder,因为这是我工作场所安装的默认编码器。
注意:
plt.ion()
打开交互模式(默认情况下已在PyCharm中打开)%cpaste
,%paste
)所有命令(plt.close()
除外)然后键入plt.close()
时,IPython或PyCharm中的代码退出时没有错误手动plt.close()
替换为plt.clf()
时,plt.close()
,例如用于在具有不同参数的循环中创建动画,其中图形需要从头开始重新创建time.sleep(1)
之前插入plt.close()
时,下面给出了一个最小的,完整的(希望)可验证的例子:
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'
虽然程序在上面列表中手动关闭窗口时继续运行没有错误,但这是一个烦人的错误(想想循环中的多个动画)。该错误也出现在例如1D线图。感谢您提供任何帮助(并澄清此错误消息的确切含义)!
答案 0 :(得分:1)
错误来自关闭图形时仍在运行的动画。虽然在大多数情况下,关闭图形时会自动停止动画,但在交互模式下似乎并非如此。
解决方案可以是在关闭图形之前明确地停止动画并将其删除。
ani = animation.FuncAnimation(...)
ani.save(...)
ani.event_source.stop()
del ani
plt.close()
答案 1 :(得分:0)
在这种情况下,您可以使用exit()