问题描述
如果我使用代码创建文件test.py
If I create a file test.py
with the code
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
if __name__ == '__main__':
fig = plt.figure()
title = fig.suptitle("Test _")
def anim(i):
title.set_text("Test %d" % i)
plt.plot([0,1], [0,1])
FuncAnimation(fig, anim)
plt.show()
并尝试使用python test.py
在命令行中运行它,我得到一个空白屏幕,标题为Test _
,没有任何轴.
and try to run it in my command line, using python test.py
, I get an empty screen with the title Test _
and without any axes.
使用python -i test.py
运行时也是如此,但是如果我现在在交互式会话中输入相同的代码
The same is true when running with python -i test.py
, but if I now enter the same code in the interactive session
>>> fig = plt.figure()
>>> title = fig.suptitle("Test _")
>>> FuncAnimation(fig, anim)
>>> plt.show()
一切正常.
我已经研究了很久了,但似乎没有发现任何与此相关的问题.我在OS X的python 3.5.2中使用matplotlib 2.0.0.
I have been looking at this for so long now and I don't seem to find any issues or questions that are related to this. I am using matplotlib 2.0.0 in python 3.5.2 on OS X.
这是(已知)错误吗?任何有想法为什么会发生这种情况或如何解决的人?
Is this a (known) bug? Anyone with ideas why this might be happening or how this could be resolved?
推荐答案
来自动画文档:"[..]保留对实例对象的引用至关重要."
From the animation documentation: "[..] it is critical to keep a reference to the instance object."
因此,您需要通过将FuncAnimation实例分配给变量来使其保持活动状态.
So you need to keep the FuncAnimation instance alive by assigning it to a variable.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
if __name__ == '__main__':
fig = plt.figure()
title = fig.suptitle("Test _")
def anim(i):
title.set_text("Test %d" % i)
plt.plot([0,1], [0,1])
ani = FuncAnimation(fig, anim)
plt.show()
关于
Animation
是否应在内部存储的问题,有正在进行的讨论. There is an ongoing discussion about whether the
Animation
should be stored internally or not. 这篇关于为什么matplotlib动画只能在交互式会话中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!