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

16,304

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

Share:
16,304
foghorn
Author by

foghorn

Updated on June 01, 2022

Comments

  • foghorn
    foghorn almost 2 years

    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?

  • Brick
    Brick about 6 years
    This should be the default!
  • creanion
    creanion almost 2 years
    I think you'll need a plt.close() after show - otherwise the jupyterlab hooks will show the figures again at the end