Feeds:
Posts
Comments

Archive for April, 2012

Python: basic drawings

It is a common task to add simple drawings like circle, ellipse, rectangle, … to a plot or 2D map. The following figure shows an example.

Example of simple drawing with Matplotlib.

I used Matplotlib to create these drawings. That is very simple and straightforward. The code also shows how to use hatching:

import pylab, numpy

from matplotlib.patches import Ellipse, Circle, Arc, Arrow, Rectangle, Polygon, RegularPolygon

x = numpy.random.normal(3., 1., (100,100))  # generate a random map
exten = array([0, 100, 0, 100])

ax = figure().add_subplot(111)
im = imshow(x,  origin=’lower’,cmap=cm.gray,extent=exten)  # create the base map
ax.yaxis.set_minor_locator(MultipleLocator(5))
ax.xaxis.set_minor_locator(MultipleLocator(5))
#——————————————————————–
ells = [Ellipse(xy=[34.2, 45], width=36, height=18, angle=21)]  # Ellipse
ax.add_artist(ells[0])
ells[0].set_clip_box(ax.bbox)
ells[0].set_fill(False)
ells[0].set_linestyle(‘solid’)
ells[0].set_lw(3)
ells[0].set_color(‘Lime’)
#——————————————————————–
arcs = [Arc(xy=[74.2, 15], width=25, height=38, angle=21, theta1=18, theta2=249, hatch=’/’)] # Arc
ax.add_artist(arcs[0])
arcs[0].set_lw(3)
arcs[0].set_color(‘Cyan’)
#——————————————————————–
rects = [Rectangle(xy=[24.2, 79], width=22, height=14, hatch=’o’)]  # filled rectangle
ax.add_artist(rects[0])
rects[0].set_lw(3)
rects[0].set_color(‘pink’)
#——————————————————————–
rects = [Rectangle(xy=[24.2, 25], width=48, height=18, fill=False)]     # empty rectangle
ax.add_artist(rects[0])
rects[0].set_lw(3)
rects[0].set_color(‘yellow’)
#——————————————————————–
ax.add_patch(Polygon([[0,0],[14,21.1],[10,40], [26,72.5],[2,89.4]], closed=True,fill=False, hatch=’\\’, color=’Brown’, lw=2.4))   # Irregular Polygon
#——————————————————————–
ax.add_patch(RegularPolygon(xy=[70,60], numVertices=8, radius=14,fill=True, color=’Orange’, hatch=’x’, ec=’k’))   # Regular Polygon
#——————————————————————–
circs = [Circle(xy=[74.2, 75], radius=18)]
ax.add_artist(circs[0])
circs[0].set_clip_box(ax.bbox)
circs[0].set_fill(False)
circs[0].set_linestyle(‘dashed’)
circs[0].set_lw(3)
circs[0].set_color(‘red’)
ax.set_xlim(exten[0], exten[1])
ax.set_ylim(exten[2], exten[3])
#——————————————————————–
show()

Advertisements

Read Full Post »