0

There are a lot of questions regarding how to use matplotlib, especially for how to either update or output a new chart per loop iteration. In particular this question is in relation to matplotlib and jupyter-notebook

For example:

Use a loop to plot n charts Python

The answer is as follows:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])

which appears to work...

until we add anything else:

for example, add a sleep statement after each plot:

import matplotlib.pyplot as plt
from time import sleep
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    sleep(2)

and suddenly it doesn't work.

One can also use any form of print to see the same issue

import matplotlib.pyplot as plt
from time import sleep
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    print('loop: ', i)

So how can I print out a new plot for each loop in a jupyter-notebook?

2
  • What exactly "does not work"? If running the above, the result is as expected and four plots are shown. Commented Nov 17, 2017 at 13:42
  • @ImportanceOfBeingErnest yes, the four plots are made, which is fine. I want them to output during the loop iterations. As it stands, the four plots are rendered after the computation ends Commented Nov 17, 2017 at 14:33

1 Answer 1

1

You have to call plt.pause(1) after each iteration to tell matplotlib to pause for 1 second and redraw the figures (https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.pause.html)

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    plt.pause(1)

Now the figures are drawn after each iteration.

Sign up to request clarification or add additional context in comments.

Comments

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.