8
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.

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

2 Comments

This does not seem to work in VSCode Python Interactive
@Vedant: Bokeh worked quite well with VSCode Python Interactive. I found this brief example, included prints before and after the code and everything showed up as I expected: donjayamanne.github.io/pythonVSCodeDocs/docs/jupyter_examples/…
1

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()

2 Comments

This does not seem to work in VSCode Python Interactive
@Vedant: Bokeh worked quite well with VSCode Python Interactive. I found this brief example, included prints before and after the code and everything showed up as I expected: donjayamanne.github.io/pythonVSCodeDocs/docs/jupyter_examples/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.