Simple way to draw 3D random walk using Python and Matplotlib.pyplot


The result is:

Simple way to draw 3D random walk using Python and Matplotlib.pyplot


This code shows the simple way to dray 3D random walk with colored line using python.

In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Generate the randam walk data.
In [2]:
N = 2000
R = (np.random.rand(N)*6).astype("int")
x = np.zeros(N)
y = np.zeros(N)
z = np.zeros(N)
x[ R==0 ] = -1; x[ R==1 ] = 1
y[ R==2 ] = -1; y[ R==3 ] = 1
z[ R==4 ] = -1; z[ R==5 ] = 1
x = np.cumsum(x)
y = np.cumsum(y)
z = np.cumsum(z)
Plot with same color.
In [3]:
plt.figure()
ax = plt.subplot(1,1,1, projection='3d')
ax.plot(x, y, z,alpha=0.6)
ax.scatter(x[-1],y[-1],z[-1])
plt.show()
Plot with changing color.
In [4]:
plt.figure()
ax = plt.subplot(1,1,1, projection='3d')
cm = plt.get_cmap('jet')
ax.set_prop_cycle('color',[cm(1.*i/(x.shape[-1]-1)) for i in range(x.shape[-1]-1)])
for i in range(x.shape[-1]-1):
    ax.plot([x[i+1],x[i]], [y[i+1],y[i]], [z[i+1],z[i]],alpha=0.6)
ax.scatter(x[-1],y[-1],z[-1],facecolor=cm(1))
plt.savefig('3d_random_walk_static.png', bbox_inches='tight', pad_inches=0.02, dpi=250)
plt.show()