randomWalk.py

#
# Random walk 
# Vincent Legat - 2024
# Ecole Polytechnique de Louvain
#

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani
plt.rcParams['toolbar'] = 'None'
plt.rcParams['figure.facecolor'] = 'lavender'
plt.rcParams['axes.facecolor'] = 'lavender'



def main() :
    fig = plt.figure("Random Walk Animation")
    ax = plt.gca()
    ax.set_xlim(-2,2)
    ax.set_ylim(-2,2)
    ax.set_aspect('equal')
    plt.axis('off')    
    circle = plt.Circle((0,0),1.5,fill=True,alpha=0.2,color='blue')
    line1, = plt.plot([],[],'-',color='blue')
    line2, = plt.plot([],[],'o',markersize=20,color='red')
    ax.add_artist(circle)
    x = np.zeros(2001) * np.nan; x[0] = 0
    y = np.zeros(2001) * np.nan; y[0] = 0
     
    def animate(frame):
        x[frame+1] = x[frame] + 0.1*(np.random.rand()-0.5)
        y[frame+1] = y[frame] + 0.1*(np.random.rand()-0.5)
        line1.set_data(x,y)
        line2.set_data([x[frame+1]],[y[frame+1]])
        return line1,line2,
        
          
   
    animation = ani.FuncAnimation(fig,animate,frames=2000,interval=50,repeat=False)
 #   animation.save('randomWalk.mp4', writer='ffmpeg')
    plt.show()

main()