Skip to content

Instantly share code, notes, and snippets.

@alexrutherford
Last active August 13, 2016 16:46
Show Gist options
  • Save alexrutherford/b8657a6cf6337aa52d5ac0df41308e27 to your computer and use it in GitHub Desktop.
Save alexrutherford/b8657a6cf6337aa52d5ac0df41308e27 to your computer and use it in GitHub Desktop.
Function to plot chloropleth map from shapefiles
import shapefile
import seaborn as sns
sf = shapefile.Reader("voronoi/voronoi.shp")
shapes = sf.shapes()
def getMid(bbox):
'''
Helper function to get midpoint of a bounding box
'''
x=bbox[0]+((bbox[2]-bbox[0])/2)
y=bbox[1]+((bbox[3]-bbox[1])/2)
return (x,y)
def plotCholoropleth(vals,fileName=None,labels=None,title=None):
'''
Plots Poygons in global variable shapes and fills
with @vals. Places in quartile buckets for range 0-1
'''
#colours=sns.color_palette(n_colors=nColours)
colours=sns.color_palette("RdBu",n_colors=4)
assert min(vals)>-0.0001 and max(vals)<1.000001
fig=plt.figure()
ax=fig.add_subplot(111)
for nshp in xrange(len(shapes)):
ptchs = []
pts = np.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]]))
plt.plot(pts[par[pij:0],par[pij+1:1]])
if labels:
(x,y)=getMid(shapes[nshp].bbox)
plt.annotate(s=towers[nshp],xy=(x,y),xycoords='data',size=6)
if vals[nshp]<0.25:
colour=colours[0]
elif vals[nshp]<0.5:
colour=colours[1]
elif vals[nshp]<0.75:
colour=colours[2]
else:
colour=colours[3]
ax.add_collection(PatchCollection(ptchs,edgecolor='white', linewidths=0.2,color=colour,alpha=1.0))
rangeStrings=['$\phi <$0.25','0.25$<\phi<$0.5','0.5$<\phi<$0.75','0.75$<\phi<$1.0']
for n,c in enumerate(colours):
plt.annotate(s=rangeStrings[n],xy=(0.1,0.25-(n*0.07)),xycoords='figure fraction',color=c,size=16)
if title:
plt.title(title,size=18)
plt.axis('off')
###############################################################################################################################
### Inset
axins = inset_axes(ax,width="30%",height="30%",loc=1)
for nshp in xrange(len(shapes)):
ptchs = []
pts = np.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]]))
plt.plot(pts[par[pij:0],par[pij+1:1]])
if vals[nshp]<0.25:
colour=colours[0]
elif vals[nshp]<0.5:
colour=colours[1]
elif vals[nshp]<0.75:
colour=colours[2]
else:
colour=colours[3]
axins.add_collection(PatchCollection(ptchs,edgecolor='white', linewidths=0.2,color=colour,alpha=1.0))
plt.xlim(-13.3,-13.08)
plt.ylim(8.32,8.6)
plt.xticks([],[])
plt.yticks([],[])
axins.spines['bottom'].set_color('grey')
axins.spines['top'].set_color('grey')
axins.spines['right'].set_color('grey')
axins.spines['left'].set_color('grey')
#plt.tight_layout()
if fileName:
plt.savefig('images/%s' % fileName,dpi=250)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment