Skip to content

Python Matplotlib animation

import numpy as np
from matplotlib import pyplot as plt
from celluloid import Camera

N = 100
noise = np.random.normal(0,5,N)

x = np.linspace(0,N-1,N)
y = noise
std = np.zeros(N)
unc = np.zeros(N)
for i in range(1,N):
   std[i] = np.std(y[:i],ddof=1)
   unc[i] = std[i]/np.sqrt(i)
std[1] = 0
unc[1] = 0

ymax = np.max([np.max(y),abs(np.min(y))])
ymin = -ymax

fig, axs = plt.subplots(2,2,dpi=300)
fig.subplots_adjust(wspace=0.4,hspace=0.8)

camera = Camera(fig)
for i in range(N):
   axs[0,0].plot(x[:int(i+1)],y[:int(i+1)],'k.')
   axs[0,1].hist(y[:int(i+1)],bins=20,color='b',range=(ymin,ymax))
   axs[0,1].axvline(x=np.mean(y[:int(i+1)]),color='r')
   axs[1,0].plot(x[:int(i+1)],std[:int(i+1)],color='k')
   axs[1,1].plot(x[:int(i+1)],unc[:int(i+1)],color='k')
   camera.snap()

animation = camera.animate(interval=100, blit=True)  
animation.save('test.mp4’)