Note

Go to the endto download the full example code.

Animated 3D random walk#

Output generated viamatplotlib.animation.Animation.to_jshtml.

importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.animationasanimation# Fixing random state for reproducibilitynp.random.seed(19680801)defrandom_walk(num_steps,max_step=0.05):"""Return a 3D random walk as (num_steps, 3) array."""start_pos=np.random.random(3)steps=np.random.uniform(-max_step,max_step,size=(num_steps,3))walk=start_pos+np.cumsum(steps,axis=0)returnwalkdefupdate_lines(num,walks,lines):forline,walkinzip(lines,walks):line.set_data_3d(walk[:num,:].T)returnlines# Data: 40 random walks as (num_steps, 3) arraysnum_steps=30walks=[random_walk(num_steps)forindexinrange(40)]# Attaching 3D axis to the figurefig=plt.figure()ax=fig.add_subplot(projection="3d")# Create lines initially without datalines=[ax.plot([],[],[])[0]for_inwalks]# Setting the Axes propertiesax.set(xlim3d=(0,1),xlabel='X')ax.set(ylim3d=(0,1),ylabel='Y')ax.set(zlim3d=(0,1),zlabel='Z')# Creating the Animation objectani=animation.FuncAnimation(fig,update_lines,num_steps,fargs=(walks,lines),interval=100)plt.show()

Tags:component: animationplot-type: 3D

Total running time of the script: (0 minutes 6.260 seconds)

Gallery generated by Sphinx-Gallery