Python Tutorial – How to Create Complex Polygon with Pyshp

pyshppython

using the pyshp library (https://code.google.com/p/pyshp/) I am trying to create a "complex" polgon with one hole inside the main-poly plus one island-poly. It should look like this:

enter image description here

I used the following code from the documentation, only changing the number of points and using anticlockwise rotation for the hole:

import shapefile
w = shapefile.Writer(shapefile.POLYGON)
w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50],[10,40],[10,10],[30,10],[30,40],[10,40],[70,20],[100,20],[100,0],[70,0],[70,20]]])
w.field('FIRST_FLD','C','40')
w.field('SECOND_FLD','C','40')
w.record('Poly','PolyTest')
w.save('TESTPOLY')

I get this:
enter image description here

Best Answer

Each piece of your complex polygon, including the hole, is called a "part" in the shapefile spec. Parts are how they tie multiple distinct geometries to a single dbf record.

In pyshp, parts are a list of lists passed to the poly method. The example you followed only has one list of points within the parts. But your shapefile has 3 distinct polygons. So each one of your 3 shapes needs to be in a sub-list like this:

w.poly(parts=[[[0,50],[50,50],[50,0],[0,0],[0,50]],[[10,40],[10,10],[30,10],[30,40],[10,40]],[[70,20],[100,20],[100,0],[70,0],[70,20]]])

enter image description here