Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically update plot in iPython notebook

As referred in this question, I am trying to update a plot dynamically in an iPython notebook (in one cell). The difference is that I don't want to plot new lines, but that my x_data and y_data are growing at each iteration of some loop.

What I'd like to do is:

import numpy as np
import time
plt.axis([0, 10, 0, 100]) # supoose I know what the limits are going to be
plt.ion()
plt.show()
x = []
y = []
for i in range(10):
     x = np.append(x, i)
     y = np.append(y, i**2)
     # update the plot so that it shows y as a function of x
     time.sleep(0.5) 

but I want the plot to have a legend, and if I do

from IPython import display
import time
import numpy as np
plt.axis([0, 10, 0, 100]) # supoose I know what the limits are going to be
plt.ion()
plt.show()
x = []
y = []
for i in range(10):
    x = np.append(x, i)
    y = np.append(y, i**2)
    plt.plot(x, y, label="test")
    display.clear_output(wait=True)
    display.display(plt.gcf())
    time.sleep(0.3)
plt.legend()

I end up with a legend which contains 10 items. If I put the plt.legend() inside the loop, the legend grows at each iteration... Any solution?

like image 888
P. Camilleri Avatar asked Aug 17 '15 13:08

P. Camilleri


People also ask

How do you dynamically update a plot in a loop 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).

What is the currently correct way to dynamically update plots in Jupyter IPython?

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.

How do you update a dynamic plot in Matplotlib?

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.


1 Answers

Currently, you are creating a new Axes object for every time you plt.plot in the loop.

So, if you clear the current axis (plt.gca().cla()) before you use plt.plot, and put the legend inside the loop, it works without the legend growing each time:

import numpy as np
import time
from IPython import display

x = []
y = []
for i in range(10):
    x = np.append(x, i)
    y = np.append(y, i**2)
    plt.gca().cla() 
    plt.plot(x,y,label='test')
    plt.legend()
    display.clear_output(wait=True)
    display.display(plt.gcf()) 
    time.sleep(0.5) 

EDIT: As @tcaswell pointed out in comments, using the %matplotlib notebook magic command gives you a live figure which can update and redraw.

like image 118
tmdavison Avatar answered Oct 16 '22 22:10

tmdavison