Plot inside a loop with Google Colabs

Viewed 1472

I am trying to have a plot inside a loop in Google Colabs. The result should be something like this plot: , produced with the following code:

plt.axis([0, 10, 0, 10])
for i in range(10):
    plt.scatter(i, i + 1)
    plt.pause(0.5)
plt.show()

However, the output is 10 plots with only one point in each, instead of having one plot, and one point added to that plot every 0.5 seconds.

I guess it has some relationship with the interactive mode and backends of Google Colab, but I've tried many things and none work. Thank you!

1 Answers

The solution is to use the display module of IPython (as found here). Also, the plt.pause(0.5) statement may cause problems, you can use the sleep function from the time module instead. The code below works for me in Google Colabs:

import matplotlib.pyplot as plt

from IPython import display
from time import sleep

plt.axis([0, 10, 0, 10])
for i in range(10):
    plt.scatter(i, i + 1)
    display.display(plt.gcf())
    display.clear_output(wait=True)
    sleep(0.5)
Related