Funcanimation Doesn't Show Outside Of Function
Solution 1:
The matplotlib documentation states about FuncAnimation
It is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers), will be garbage collected which will stop the animation.
If you put plt.show()
outside of the anim_random_points
function, the variable ani
, which holds the reference to the animation, will be garbage collected and there will be no animation to be shown any more.
The solution for that case would be to return the animation from that function
defanim_random_points(fig, axis):
# ...
ani = matplotlib.animation.FuncAnimation(...)
return ani
if __name__ == '__main__':
# ...
ani = anim_random_points(...)
plt.show()
Solution 2:
You should really ask two separate questions.
I can answer the first one. The difference between the two positions is due to the fact that ani
is a local variable to your function anim_random_points()
. It is automatically deleted when the execution reaches the end of the function. Therefore plt.show()
in position 2 has nothing to display.
If you want to use plt.show()
in position 2, you need to return the ani object from your function, and keep a reference to it in the main part of your code.
def anim_random_points(fig, axis):
(...)
ani = matplotlib.animation.FuncAnimation(...)
return ani
if __name__ == '__main__':
(...)
ani = anim_random_points(fig, axis)
# Position 2 for plt.show()
plt.show()
Post a Comment for "Funcanimation Doesn't Show Outside Of Function"