How to dynamically update a plot in a loop in Ipython notebook?

MatplotlibServer Side ProgrammingProgramming

We can iterate a plot using display.clear_output(wait=True), display.display(pl.gcf()) and time.sleep() methods in a loop to get the exact output.

Steps

  • Plot a sample (or samples) from the "standard normal" distribution using pylab.randn().

  • Clear the output of the current cell receiving output, wait=False(default value), wait to clear the output until new output is available to replace it.

  • Display a Python object in all frontends. By default, all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how, using the display() method. pl.gcf helps to get the current figure.

  • To sleep for a while, use time.sleep() method.

Example

import time
import pylab as pl
from IPython import display
for i in range(2):
   pl.plot(pl.randn(100))
   display.clear_output(wait=True)
   display.display(pl.gcf())
   time.sleep(1.0)

Output

Figure(640x480)
Figure(640x480)
raja
Published on 15-Mar-2021 08:20:00
Advertisements