File failed to load: http://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/extensions/TeX/AmsMath.js

Saturday, March 3, 2018

Very simple way to animate in Jupyter notebooks

I want to use Google Colaboratory for my python course, but the module we use for animation doesn't work there because the necessary libraries are not installed. I had planned to spend part of the weekend to see if I could find a solution but by amazing coincidence a tweet in my Twitter stream this morning had the answer!



The answer is simply to display the images sequentially and clear the output each time with clear_output(wait=True) from IPython.display. You can see the demo code I wrote below.  This works very nicely on my off-line notebook (where you want to execute this line in a cell above the notebook itself: %matplotlib inline) while the animation is a bit choppy on Colaboratory, presumably due  to network latency. But it's certainly good enough.

Thanks again to Twitter for saving me tons of time!

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
import time
n_particles = 100
for x in range(50):
clear_output(wait=True)
positions_x = [np.random.random() for i in range(n_particles)]
positions_y = [2*(np.random.random()-0.5) for i in range(n_particles)]
plt.plot(positions_x , positions_y,'ro')
plt.axis((-1.0 , 1.0 , -1.0 , 1.0))
plt.show()
time.sleep(0.01)


This work is licensed under a Creative Commons Attribution 4.0

No comments: