import matplotlib.pyplot as plt import matplotlib.path as mpath import matplotlib.patches as patches import ogr import numpy as np from copy import copy %matplotlib inline def geom2path(geom): # function to convert a OGR geometry object to # a Matplotlib Path allverts = None allcodes = None for poly in geom: for ring in poly: listring = ring.ExportToWkt().replace('LINEARRING (','').replace(')','').split(',') # itertools.izip for python 2 xs, ys = zip(*[vert.split(' ') for vert in listring]) verts = np.array([xs, ys], dtype='float32') codes = len(xs) * [mpath.Path.LINETO] # Make the first code a MOVETO, prevents # a line being drawn between parts or # between outer and inner rings. codes[0] = mpath.Path.MOVETO if not allverts is None: allverts = np.concatenate([allverts, verts], axis=1) allcodes = np.concatenate([allcodes, codes], axis=1) else: allverts = verts allcodes = codes mpl_path = mpath.Path(allverts.swapaxes(0,1), allcodes) return mpl_path # example from: # http://en.wikipedia.org/wiki/Well-known_text#Geometric_objects inwkt = 'MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 10 30, 10 10, 30 5, 45 20, 20 35),(30 20, 20 15, 20 25, 30 20)))' # parse the WKT to a OGR Geometry geom = ogr.CreateGeometryFromWkt(inwkt) mpl_path, verts, codes = geom2path(geom) # convert to Path Patch mypatch = patches.PathPatch(mpl_path, facecolor='orange', lw=2) fig, ax = plt.subplots(subplot_kw={'aspect': 1.0, 'xlim': [0, 50], 'ylim': [0,50]}) ax.add_patch(copy(mypatch))