Blog Archive

Thursday, September 13, 2012

How to Draw in Python 2


import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.transforms import Affine2D


#Different sets of dots
#=========================================================
#standard vertices
verts = [
    (0., 0.),
    (0., 4.),
    (1., 1.),
    (4., 0.),
    (0., 0.),
    ]

#rotated vertices
rotated_verts=Affine2D().rotate_deg(60).transform(verts)

#scale vertices
scaled_verts=Affine2D().scale(0.5,0.5).transform(verts)

#translated vertices
translated_verts=Affine2D().translate(2,2).transform(verts)

#How we will Connect the Dots
#==========================================================
#How we will link together these vertices
codes = [Path.MOVETO,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.CLOSEPOLY,
         ]

#Creating the paths from dot to dot
#===========================================================
path = Path(verts, codes)
rotpath=Path(rotated_verts,codes)
sclpath=Path(scaled_verts,codes)
trspath=Path(translated_verts,codes)






#plot shapes created by connecting dots
#============================================================
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111)

patch = patches.PathPatch(path, facecolor='green', lw=2,edgecolor='black',alpha=0.5)
rotatedpatch=patches.PathPatch(rotpath,facecolor='blue',lw=2,edgecolor='black',alpha=0.5)
scaledpatch=patches.PathPatch(sclpath,facecolor='red',lw=2,edgecolor='black',alpha=0.5)
translatedpatch=patches.PathPatch(trspath,facecolor='yellow',lw=1,edgecolor='black',alpha=0.5)


ax.add_patch(patch)
ax.add_patch(rotatedpatch)
ax.add_patch(scaledpatch)
ax.add_patch(translatedpatch)


ax.set_xlim(-5,5)
ax.set_ylim(-5,5)
plt.show()





This will give the figure below:

No comments:

Post a Comment