Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush plots in IPython Notebook sequentially?

for i in range(3):
   print("Info ",i)
   plt.figure()
   plt.plot(np.arange(10)*(i+1))

In an IPython Notebook, this will first print out the three info messages, and afterwards plot the three figures.

Which command can I use to enforce the sequential display of prints and plots? That is, print "Info 0", plot "Figure 0", print "Info 1", plot "Figure 1", etc.

This a simple bare-bones example. In my case it's much more complicated, and it's important to get the behavior correctly.

like image 780
user37544 Avatar asked Dec 04 '15 17:12

user37544


2 Answers

IPython first evaluates all code in your cell. When this is done, open figures are plotted to the output area.

If that's not what you want, you can display your figures manually. However you have to be sure to close all newly created figure objects before the evaluation of the cell ends.

This is a short example:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display

for i in range(3):
    print("Info ",i)
    fig, ax = plt.subplots()
    ax.plot(np.arange(10)*(i+1))
    display(fig)
    plt.close()
like image 42
cel Avatar answered Sep 30 '22 16:09

cel


Simply add plt.show() at the desired location.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

for i in range(3):
    print "Info ",i
    plt.plot(np.arange(10)*(i+1))
    plt.show()
like image 86
Marc Schulder Avatar answered Sep 30 '22 17:09

Marc Schulder