Random Walk

We all love random walks; be it just strolling through your city, forest, or a confined orthogonal canvas.

import string
from matplotlib import pyplot as plt
import random
import matplotlib.cm as cm

X,Y = 9,16  # figure ratio
m  = 2      # ratio multiplier 
fs = 3      # figure size multiplier
lw = 2      # line width
steps = 5000# the ammount of random steps

lw = 3*fs
figsize = (fs*Y,fs*X)

Y,X=Y*m,X*m

points = [(Y/2,X/2)] # start in the middle of the canvas
for i in range(steps):
    # random stepping
    x,y = points[-1]
    x += random.randint(0 if x<=1 else -1 ,0 if x>=Y else 1) 
    y += random.randint(0 if y<=1 else -1 ,0 if y>=X else 1) 
    points.append((x,y))
    

cmap = cm.Set3 # choosing colormap
fig,ax = plt.subplots(figsize=figsize)
a,b = list(zip(*points))
ln, = ax.plot(a,b,c='k',lw=lw*2) # draw a black outline
ln.set_solid_capstyle('round')   # ensure round corners

n=0
for start,end in zip(points[:-1],points[1:]):
    a,b = start
    c,d = end
    ln, = ax.plot([a,c],[b,d],c=cmap(n),lw=lw)
    ln.set_solid_capstyle('round')
    n += 1.0/len(points)
plt.axis('off')
ax.set_ylim((0,X+1))
ax.set_xlim((0,Y+1))

fname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))

plt.savefig('randWalk_{}_{}.png'.format(steps,fname))
Pin on Pinterest0Buffer this pageEmail this to someoneShare on Facebook0Share on Google+0Flattr the authorDigg thisPrint this pageTweet about this on TwitterShare on LinkedIn0Share on Reddit0Share on StumbleUpon0Share on Tumblr0

Leave a Reply