Search code examples
pythonpandasmatplotlibjupyter-notebookipython

How to dynamically update a plot in a loop in IPython notebook (within one cell)


Environment: Python 2.7, Matplotlib 1.3, IPython notebook 1.1, Linux, and Chrome. The code is in one single input cell, using --pylab=inline.

I want to use IPython notebook and Pandas to consume a stream and dynamically update a plot every five seconds.

When I just use a print statement to print the data in text format, it works perfectly fine: the output cell just keeps printing data and adding new rows. But when I try to plot the data (and then update it in a loop), the plot never shows up in the output cell. But if I remove the loop, and just plot it once, it works fine.

Then I did some simple test:

i = pd.date_range('2013-1-1',periods=100,freq='s')
while True:
    plot(pd.Series(data=np.random.randn(100), index=i))
    #pd.Series(data=np.random.randn(100), index=i).plot() also tried this one
    time.sleep(5)

The output will not show anything until I manually interrupt the process (Ctrl + M + I). And after I interrupt it, the plot shows correctly as multiple overlapped lines. But what I really want is a plot that shows up and gets updated every five seconds (or whenever the plot() function gets called, just like what print statement outputs I mentioned above, which works well). Only showing the final chart after the cell is completely done is not what I want.

I even tried to explicitly add the draw() function after each plot(), etc. None of them works. How can I dynamically update a plot by a for/while loop within one cell in IPython notebook?


Solution

  • Use the IPython.display module:

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