0

In a Coursera class about plotting in Python with Matplotlib, I was taught to make animated plots by using a FuncAnimation object. Why is this necessary? The obvious technique would be to use a for loop that updates the plot and pauses on each iteration. That seems a lot easier.

I've tried this, and it didn't work. Here's a simple example:

import matplotlib.pyplot as plt
import numpy as np
import time

%matplotlib notebook

plt.plot([0, 1, 2], [0, 1, 0])
l = plt.gca().get_children()[0]
for i in range(5):
    l.set_ydata([0, 1, i/10])
    plt.show()
    time.sleep(1)

The result is that only the final plot is shown, after a 5-second delay. Why doesn't this work?

EDIT: I should have specified that I'm running this code in a Jupyter notebook.

David Wasserman
  • 551
  • 5
  • 10
  • In principle you are correct, you may use a for loop, see e.g. [this question](https://stackoverflow.com/questions/45157538/python-matplotlib-loop-clear-and-show-different-plots-over-the-same-figure). Now are you asking why it doesn't work in jupyter notebook? – ImportanceOfBeingErnest Feb 09 '18 at 17:03
  • For ways to create animations in a jupyter notebook, see [this question](https://stackoverflow.com/questions/35532498/animation-in-ipython-notebook). – ImportanceOfBeingErnest Feb 09 '18 at 17:16
  • @ImportanceOfBeingErnest, yes, I ran my code in a Jupyter notebook, and it didn't produce the result I expected. I appreciate that second question you linked to, because it shows how to do animation with a loop in a Jupyter notebook. However, I'd also like to understand why my code didn't work. – David Wasserman Feb 09 '18 at 21:51

1 Answers1

0

For general ways to animate matplotlib plots in jupyter notebook see Animation in iPython notebook.

It should hence be noted that the problem here only occurs when using the %matplotlib notebook backend in a jupyter notebook with a python loop instead of the internal matplotlib.animation classes.

In order to ensure interactivity, the %matplotlib notebook creates the matplotlib figure using its own little application inside the jupyter output. Before this application is started, one can of course not interact with it. And as soon as this application is started, the connection to the python code from the IPython notebook is necessarily lost. This behaviour is similar to other GUIs in python: Once the GUI event loop is started, the python code stops until the GUI is closed.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712