Jupyter Notebook and Updating Plots

Dr. Shahin Rostami
2 min readOct 6, 2018

--

Sometimes you’ll want to visualise features of interest during the runtime of your code, e.g. plotting some performance metric against the number of iterations for some algorithm. If you’ve come from a different IDE, maybe even MATLAB, then you’ll know this is a trivial task. However, it takes a little bit of extra work to get similar behaviour in a Jupyter notebook (and a Kaggle Kernel notebook).

Here is an example of a visualisation that I find useful during runtime:

Now, if we want to have these real-time updates to our plots in Jupyter (including Kaggle Kernel notebooks), we need to import display and clear_output from IPython.display:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

Now we can update our plots with two different approaches. This approach clears the axes before plotting:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for i in range(20):
x = np.arange(0, i, 0.1);
y = np.sin(x)

ax.set_xlim(0, i)

ax.cla()
ax.plot(x, y)
display(fig)

clear_output(wait = True)
plt.pause(0.5)

The other approach doesn’t clear the axes before plotting:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for i in range(21):
ax.set_xlim(0, 20)

ax.plot(i, 1,marker='x')
display(fig)

clear_output(wait = True)
plt.pause(0.5)

I’ve found these snippets to be incredibly useful in order to get some real-time feedback when using Jupyter notebooks. These are just simple examples, but they can be used to create some interesting “animations” that can give you insight into your experiments during runtime.

--

--