Consider the following animation in python written in a file test.py
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig, ax = plt.subplots()
title = fig.suptitle("Test _")
p, = ax.plot([0,2], [0,1])
def anim(i):
title.set_text("Test %d" % i)
p.set_data([np.random.rand(),i], [np.random.rand(),i])
ani = FuncAnimation(fig, anim, 10, blit=False)
plt.show()
This works as expected when I run it from the command line python test.py
and also from an interactive shell: a line segment with changing start and end point is animated.
Now let's set blit=True
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time
fig, ax = plt.subplots()
p, = ax.plot([0,2], [0,1])
def init_func():
return p,
def anim(i):
p.set_data([np.random.rand(),i], [np.random.rand(),i])
return p,
ani = FuncAnimation(fig, anim, 10, blit=True, init_func=init_func)
plt.show()
This also works both on command line and interactive shell.
However, I would like to animate the title of the plot.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time
fig, ax = plt.subplots()
title = ax.set_title("Initial Title")
p, = ax.plot([0,2], [0,1])
def init_func():
return p, title
def anim(i):
title.set_text("3D Test %d" % i)
p.set_data([np.random.rand(),i], [np.random.rand(),i])
return p, title
ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()
This almost works but it two things happen:
- in interactive shell, the title stays fixed with "Initial Title". It doesn't update
- from the command line, the titles do appear and update but they all overlap each other (there is apparently no erasing previous titles when redrawing the new ones).
As you can see, the plot itself doesn't have this issue.
Why does this happen only with the Title
artist?
Finally consider the following variant of this code
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time
fig, ax = plt.subplots()
title = ax.set_title("50")
p, = ax.plot([0,2], [0,1])
def init_func():
return p,
def anim(i):
title.set_text("3D Test %d" % i)
p.set_data([np.random.rand(),i], [np.random.rand(),i])
return p,
ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()
Here we are calling title.set_text
in each update function, but the title
artist is not returned so as far as I know FuncAnimation
does not consider it as an artist to redraw.
Nonetheless, what happens is that
- from the command line the title does get updated but the plot is animated for a few frames and then disappears.
- from the interactive shell, the title just stays stuck on the initial title but the plot does work.
What is happening here?