35

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?

4
  • If you're using %matplotlib inline, you can call fig.show() when you want the plot to display, I think.
    – Thomas K
    Commented Jul 17, 2015 at 20:36
  • Edited to include %matplotlib inline. Additionally calling fig.show() after ax.hist(data) did not change the result.
    – foghorn
    Commented Jul 17, 2015 at 21:17
  • 7
    What about plt.show()?
    – Thomas K
    Commented Jul 17, 2015 at 21:31
  • 3
    plt.show() did the trick
    – foghorn
    Commented Jul 17, 2015 at 21:50

1 Answer 1

44

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

2
  • 6
    This should be the default!
    – Brick
    Commented Mar 20, 2018 at 16:27
  • I think you'll need a plt.close() after show - otherwise the jupyterlab hooks will show the figures again at the end
    – ramslök
    Commented Jun 19, 2022 at 19:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.