Visitar URL original
animation.save and fig.savefig interfere with each other and raise StopIteration · Issue #17770 · matplotlib/matplotlib · GitHub
The Wayback Machine - https://web.archive.org/web/20210831184340/https://github.com/matplotlib/matplotlib/issues/17770
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

animation.save and fig.savefig interfere with each other and raise StopIteration #17770

Closed
chisarie opened this issue Jun 26, 2020 · 4 comments
Closed

Comments

@chisarie
Copy link

@chisarie chisarie commented Jun 26, 2020

The following code snippet raises StopIteration:

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

fig, ax = plt.subplots()
plt.plot([1,2,3],[2,4,3])
def update(frame):
	return []
animation = FuncAnimation(fig, update, frames=iter(range(10)), repeat=False, blit=True, interval=100)
animation.save("hi.mp4")

fig2, ax2 = plt.subplots()
ax2.plot([7, 6, 3], [3, 5, 2])
fig2.savefig("hi.png")

The same also happens if the figure is saved before the animation.
The interesting thing is that the two parts of the script work fine when run alone, so there must be some interference between the two.

The output produced by the above code:

Traceback (most recent call last):
  File "/home/eugenio/miniconda3/envs/jax_agents_env/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 196, in process
    func(*args, **kwargs)
  File "/home/eugenio/miniconda3/envs/jax_agents_env/lib/python3.7/site-packages/matplotlib/animation.py", line 951, in _start
    self._init_draw()
  File "/home/eugenio/miniconda3/envs/jax_agents_env/lib/python3.7/site-packages/matplotlib/animation.py", line 1743, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
StopIteration

Matplotlib version

  • Operating system: Ubunut 18.04
  • Matplotlib version: 3.2.2
  • Matplotlib backend (print(matplotlib.get_backend())): TkAgg
  • Python version: 3.7.7
  • Jupyter version (if applicable): No Jupyter
  • Other libraries:

Matplotlib installed using pip inside a conda environment

@anntzer
Copy link
Contributor

@anntzer anntzer commented Jun 26, 2020 •

Looks like this basically comes from trying to re-draw() a figure hosting an non-repeating animation, after the animation has finished running (tbh it's not clear to me what the semantics should be). In the OP's example this comes from savefig() returning to the event loop, but this can be triggered with a single figure with

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

fig, ax = plt.subplots()
plt.plot([1,2,3],[2,4,3])
def update(frame):
	return []
animation = FuncAnimation(fig, update, frames=iter(range(10)), repeat=False, blit=True, interval=100)
animation.save("hi.mp4")

fig.canvas.draw()

and appears to throw at least as far back as 3.0.

@chisarie
Copy link
Author

@chisarie chisarie commented Jun 29, 2020

Hi @anntzer, thank you for your answer! In my application the animation and the figure to save are completely unrelated, they even live in different files, nevertheless I am experiencing this issue. If you have any tips on how to overcome this, please let know :).

@tacaswell
Copy link
Member

@tacaswell tacaswell commented Jun 30, 2020

ok, I understand @anntzer 's minimal reproduction case (the animation installis a single-shot callback to run after the first draw to start the "live" animation, we exhaust the data source before it gets drawn so the callback fails.

On tkagg I get a much deeper callback which shows this:


In [1]: import matplotlib.pyplot as plt 
   ...: from matplotlib.animation import FuncAnimation 
   ...:  
   ...: fig, ax = plt.subplots() 
   ...: plt.plot([1,2,3],[2,4,3]) 
   ...: def update(frame): 
   ...: ^Ireturn [] 
   ...: animation = FuncAnimation(fig, update, frames=iter(range(10)), repeat=False, blit=True, interval=100) 
   ...: animation.save("hi.mp4") 
   ...:  
   ...: fig.canvas.draw()                                                                                                                                            
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-1-8ae542acb6bd> in <module>
      8 animation = FuncAnimation(fig, update, frames=iter(range(10)), repeat=False, blit=True, interval=100)
      9 animation.save("hi.mp4")
---> 11 fig.canvas.draw()

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/backends/backend_tkagg.py in FigureCanvasTkAgg.draw(self)
      8 def draw(self):
----> 9     super(FigureCanvasTkAgg, self).draw()
     10     _backend_tk.blit(self._tkphoto, self.renderer._renderer, (0, 1, 2, 3))
     11     self._master.update_idletasks()

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/backends/backend_agg.py in FigureCanvasAgg.draw(self)
    403 # Acquire a lock on the shared font cache.
    404 with RendererAgg.lock, \
    405      (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
    406       else nullcontext()):
--> 407     self.figure.draw(self.renderer)
    408     # A GUI class may be need to update a window using this draw, so
    409     # don't forget to call the superclass.
    410     super().draw()

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/artist.py in allow_rasterization.<locals>.draw_wrapper(artist, renderer, *args, **kwargs)
     38     if artist.get_agg_filter() is not None:
     39         renderer.start_filter()
---> 41     return draw(artist, renderer, *args, **kwargs)
     42 finally:
     43     if artist.get_agg_filter() is not None:

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/figure.py in Figure.draw(self, renderer)
   1865 finally:
   1866     self.stale = False
-> 1868 self.canvas.draw_event(renderer)

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/backend_bases.py in FigureCanvasBase.draw_event(self, renderer)
   1757 s = 'draw_event'
   1758 event = DrawEvent(s, self, renderer)
-> 1759 self.callbacks.process(s, event)

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/cbook/__init__.py in CallbackRegistry.process(self, s, *args, **kwargs)
    228 except Exception as exc:
    229     if self.exception_handler is not None:
--> 230         self.exception_handler(exc)
    231     else:
    232         raise

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/cbook/__init__.py in _exception_printer(exc)
     80 def _exception_printer(exc):
     81     if _get_running_interactive_framework() in ["headless", None]:
---> 82         raise exc
     83     else:
     84         traceback.print_exc()

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/cbook/__init__.py in CallbackRegistry.process(self, s, *args, **kwargs)
    223 if func is not None:
    224     try:
--> 225         func(*args, **kwargs)
    226     # this does not capture KeyboardInterrupt, SystemExit,
    227     # and GeneratorExit
    228     except Exception as exc:

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/animation.py in Animation._start(self, *args)
    947 self._fig.canvas.mpl_disconnect(self._first_draw_id)
    949 # Now do any initial draw
--> 950 self._init_draw()
    952 # Add our callback for stepping the animation and
    953 # actually start the event_source.
    954 self.event_source.add_callback(self._step)

~/.virtualenvs/bleeding/lib/python3.10/site-packages/matplotlib/animation.py in FuncAnimation._init_draw(self)
   1688 def _init_draw(self):
   1689     # Initialize the drawing either using the given init_func or by
   1690     # calling the draw function with the first item of the frame sequence.
   1691     # For blitting, the init_func should return a sequence of modified
   1692     # artists.
   1693     if self._init_func is None:
-> 1694         self._draw_frame(next(self.new_frame_seq()))
   1696     else:
   1697         self._drawn_artists = self._init_func()

StopIteration: 

I am however at a loss for how @chisarie is triggering this issue and why saving a different figure would trigger this. If I run the code in the OP as a script (via python test.py) then I don't get a trace back so I suspect that does have something to do with coming back to the prompt (and something pulling up the GUI window). I'll have a PR to fix this open later tonight (have a fix, just need to write the test).

@tacaswell tacaswell added this to the v3.4.0 milestone Jun 30, 2020
tacaswell added a commit to tacaswell/matplotlib that referenced this issue Jul 1, 2020
If `_init_draw()` fails, assume the animation is dead, but do not fail.

closes matplotlib#17770
@tacaswell
Copy link
Member

@tacaswell tacaswell commented Jul 1, 2020

I put up a draft PR, but I'm no longer sure it is right or if there is something deeper that we need to sort out.

@QuLogic QuLogic removed this from the v3.4.0 milestone Jan 27, 2021
@QuLogic QuLogic added this to the v3.5.0 milestone Jan 27, 2021
tacaswell added a commit to tacaswell/matplotlib that referenced this issue Aug 5, 2021
If `_init_draw()` fails, assume the animation is dead, but do not fail.

closes matplotlib#17770
tacaswell added a commit to tacaswell/matplotlib that referenced this issue Aug 6, 2021
If we need to get the first frame in `_init_draw()` (because the user did not
pass an initialization function) fails, warn instead of raising.

closes matplotlib#17770
aitikgupta added a commit to aitikgupta/matplotlib that referenced this issue Aug 13, 2021
If we need to get the first frame in `_init_draw()` (because the user did not
pass an initialization function) fails, warn instead of raising.

closes matplotlib#17770
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

4 participants