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

后端 未结 6 1517
梦如初夏
梦如初夏 2020-11-28 02:19

Environment: Python 2.7, matplotlib 1.3, IPython notebook 1.1, linux, chrome. The code is in one single input cell, using --pylab=inline

I want to use I

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 02:28

    A couple of improvement's on HYRY's answer:

    • call display before clear_output so that you end up with one plot, rather than two, when the cell is interrupted.
    • catch the KeyboardInterrupt, so that the cell output isn't littered with the traceback.
    import matplotlib.pylab as plt
    import pandas as pd
    import numpy as np
    import time
    from IPython import display
    %matplotlib inline
    
    i = pd.date_range('2013-1-1',periods=100,freq='s')
    
    while True:
        try:
            plt.plot(pd.Series(data=np.random.randn(100), index=i))
            display.display(plt.gcf())
            display.clear_output(wait=True)
            time.sleep(1)
        except KeyboardInterrupt:
            break
    

提交回复
热议问题