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?
Try to add show() or gcf(). show() after the plot() function. These will force the current figure to update (gcf() returns a reference for the current figure).
We can use matplotlib to update a plot on every iteration during the loop. With the help of matplotlib. pyplot. draw() function we can update the plot on the same figure during the loop.
What is the currently correct way to dynamically update plots in Jupyter/iPython? We can first activate the figure using plt. ion() method. Then, we can update the plot with different sets of values.
To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data. to define the update_line function. In it, we call set_xdata to set the data form the x-axis. And we call set_ydata to do the same for the y-axis.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With