Python matplotlib's FuncAnimation does not close correctly with internal Latex rendering and PyCharm?

See also https://stackoverflow.com/questions/59898647/python-matplotlibs-funcanimation-does-not-close-correctly-with-internal-latex-r

Using matplotlib's FuncAnimation to create an animation, I get the error message

Traceback (most recent call last):
  File "/scratch/seismo_proxauf/.conda/envs/proxconda3/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 216, in process
    func(*args, **kwargs)
  File "/scratch/seismo_proxauf/.conda/envs/proxconda3/lib/python3.7/site-packages/matplotlib/animation.py", line 957, in _start
    self.event_source.add_callback(self._step)
AttributeError: 'NoneType' object has no attribute 'add_callback'

after successfully saving the animation. The plot also reopens after closing briefly. Below is a minimal example. The error can be activated/deactivated by setting the flag error_trigger to True and False respectively. It seems to have to do with the internal latex rendering. The %d format string in the axis title string is crucial, without any string insertion the code seems to always work. The extra commands after saving the animation are used because of my earlier Stackoverflow question.

Note: This error occurs when using PyCharm interactively (mark code and press Ctrl+Alt+E), but not in a default terminal (python test_animation.py).

Specifications: Python 3.7.6, matplotlib 3.1.2, ffmpeg 4.2, PyCharm 2019.3.1 Community Edition

What causes this error message and how can it be avoided (even with PyCharm)?

Update: When running the code multiple times with the error activated, subsequent animations will close correctly and won't show the error message anymore. The plot window of the first animation will stay open however.


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# plt.ion()

def animate(iter_temp, error_trigger_temp):
    ax = plt.gca()
    plt.imshow(np.random.rand(10,10))
    if error_trigger_temp == True:
        ax.set_title(r'$t_a$, timestep %d' % (iter_temp))
    else:
        ax.set_title('t_a, timestep %d' % (iter_temp))

error_trigger = True

iter = np.arange(10)

fig = plt.figure()
myani = FuncAnimation(fig, animate, frames=iter, fargs=(error_trigger,), interval=50)
myani.save('~/test_animation.mp4', writer='ffmpeg')
myani.event_source.stop()
del myani
plt.close()

Please sign in to leave a comment.