Skip to content

Instantly share code, notes, and snippets.

@vane
Created May 7, 2017 18:42
Show Gist options
  • Save vane/de27ccbf4f20e11e74359d6665df3ce9 to your computer and use it in GitHub Desktop.
Save vane/de27ccbf4f20e11e74359d6665df3ce9 to your computer and use it in GitHub Desktop.
draw-world-python-geojson-matplotlib
#!/usr/bin/python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
from descartes import PolygonPatch
import simplejson
import os
#https://github.com/mledoze/countries/data
BASE_PATH = "your path to data folder"
# some random 0-255 utility
r = lambda: random.randint(0,255)
# get all files from path of given extension
def getFiles(path, ext):
dir = os.listdir(path)
k = len(dir)
i = 0
while i != k:
f = dir[i]
if f[len(f)-4:] != ext:
dir.pop(i)
i-=1
i+=1
k = len(dir)
return dir
# get json from file
def getJSON(path):
f = open(path)
return simplejson.loads(f.read())
# plot path
def plotFeature(fig, geom):
if geom['type'] == 'Polygon':
poly = geom
color = '#%02X%02X%02X' % (r(),r(),r())
fig.add_patch(PolygonPatch(poly, fc=color, ec=color, alpha=1, zorder=2))
elif geom['type'] == 'MultiPolygon':
for c in geom['coordinates']:
poly = {"type": "Polygon", "coordinates": c}
#print "add path"
color = '#%02X%02X%02X' % (r(),r(),r())
fig.add_patch(PolygonPatch(poly, fc=color, ec=color, alpha=1, zorder=2))
def start():
files = getFiles(BASE_PATH, 'json')
print files
#create figure
fig = plt.subplot()
# list directory files
for f in files:
path = BASE_PATH+f
# get json data
pydata = getJSON(path)
print "draw : "+f
# check if has geometry
if pydata['features'][0].has_key('geometry'):
geom = pydata['features'][0]['geometry']
print geom['type']
plotFeature(fig, geom)
# scale and remove axis
fig.axis('scaled')
fig.axis('off')
#save the plot as an image
plt.savefig('world.png')
if __name__ == "__main__":
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment