Search This Blog

Saturday, 18 March 2017

Python program for visualisation of shapefile


import shapefile
import matplotlib.pyplot as plt
from numpy import array
from numpy import arange
import matplotlib.cm as cm
import matplotlib.patches as patches
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
sf = shapefile.Reader('D:/vector/India/IND_adm3.shp')

recs = sf.records()
shapes = sf.shapes()
Nshp = len(shapes)
cns =[]
for nshp in xrange(Nshp):
    cns.append(recs[nshp][1])
cns = array(cns)
cm = cm.get_cmap('Dark2')
cccol = cm(1.*arange(Nshp)/Nshp)
# --plot--
fig = plt.figure()
ax = fig.add_subplot(111)
for nshp in xrange(Nshp):
    ptchs = []
    pts = array(shapes[nshp].points)
    prt = shapes[nshp].parts
    par = list(prt) + [pts.shape[0]]
    for pij in xrange(len(prt)):
        ptchs.append(Polygon(pts[par[pij]:par[pij + 1]]))
        ax.add_collection(PatchCollection(ptchs,facecolor = cccol[nshp,:],\
                          edgecolor = 'k', linewidths =.1))
ax.set_xlim(-180,+180)
ax.set_ylim(-90,90)
##fig.savefig('test.png')
plt.show()
     

No comments:

Post a Comment