pythonloopsmatplotlibanimationfigure

How to show one figure in loop in Python?


I want to show a figure that is calculated in a loop, let say with 5 iterations.

This is the code that I wrote

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,1,100)
y = np.linspace(0,1,100)
xx,yy = np.meshgrid(x,y)

for n in range(5):
  a = np.sin(xx-2*n)
  plt.imshow(a,interpolation='bilinear')
  plt.show()

With this code, I got 5 figures. How to make it runs in one figure for each iteration? I used google collab, is it possible to make the result (figure) opened in new window (undocked) like in matlab?


Solution

  • You can simulate an animation by using a display/clear_output from (used by Colab):

    import time
    
    import matplotlib.pyplot as plt
    import numpy as np
    from IPython.display import clear_output, display
    
    x = np.linspace(0, 1, 100)
    y = np.linspace(0, 1, 100)
    xx, yy = np.meshgrid(x, y)
    
    # you could initialize a subplots or whatever here..
    
    for n in range(5):
        a = np.sin(xx - 2 * n)
        plt.imshow(a, interpolation="bilinear")
        # this one is optional (to verbose my output)
        plt.gca().set_title(f"Plot n°{n+1}", fontweight="bold")
        # added these three lines
        display(plt.gcf())
        clear_output(wait=True)
        time.sleep(0.5)
    
    plt.show();
    

    NB: This works in any IPython environment (e.g., Jupyter, Colab, ..).

    enter image description here