Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display print statements interlaced with matplotlib plots inline in Ipython?

I would like to have the output of print statements interlaced with plots, in the order in which they were printed and plotted in the Ipython notebook cell. For example, consider the following code:

(launching ipython with ipython notebook --no-browser --no-mathjax)

%matplotlib inline
import matplotlib.pyplot as plt

i = 0
for data in manydata:
    fig, ax = plt.subplots()
    print "data number i =", i
    ax.hist(data)
    i = i + 1

Ideally the output would look like:

data number i = 0
(histogram plot)
data number i = 1
(histogram plot)
...

However, the actual output in Ipython will look like:

data number i = 0
data number i = 1
...
(histogram plot)
(histogram plot)
...

Is there a direct solution in Ipython, or a workaround or alternate solution to get the interlaced output?

like image 730
foghorn Avatar asked Jul 17 '15 19:07

foghorn


People also ask

What is the %Matplotlib inline?

You can use the magic function %matplotlib inline to enable the inline plotting, where the plots/graphs will be displayed just below the cell where your plotting commands are written. It provides interactivity with the backend in the frontends like the jupyter notebook.

Do We Still Need %Matplotlib inline?

So %matplotlib inline is only necessary to register this function so that it displays in the output. Running import matplotlib. pyplot as plt also registers this same function, so as of now it's not necessary to even use %matplotlib inline if you use pyplot or a library that imports pyplot like pandas or seaborn.


1 Answers

There is simple solution, use matplotlib.pyplot.show() function after plotting.

this will display graph before executing next line of the code

%matplotlib inline import matplotlib.pyplot as plt  i = 0 for data in manydata:     fig, ax = plt.subplots()     print "data number i =", i     ax.hist(data)     plt.show() # this will load image to console before executing next line of code     i = i + 1 

this code will work as requested

like image 119
Rahul Gupta Avatar answered Oct 03 '22 05:10

Rahul Gupta