Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swapping coordinates with Fiona
# Swapping x, y coords.
from descartes import PolygonPatch
from fiona import collection
from itertools import imap
import logging
from matplotlib import pyplot
log = logging.getLogger()
BLUE = '#6699cc'
# To begin: a few functions to swap geometry coordinates. They call each
# other semi-recursively. GeoJSON was designed to make this possible, BTW.
def swap_Point(coords):
"""Swaps x, y coordinate values, leaves z+ alone."""
return tuple(coords[:2][::-1] + coords[2:])
def swap_LineString(coords):
"""Returns swapped LineString or Ring coordinates, preserving
order, number, and dimensionality."""
# Calls swap_Point.
return list(swap_Point(pt_coords) for pt_coords in coords)
def swap_Polygon(coords):
"""Returns swapped Polygon coordinates, preserving order, number,
and dimensionality."""
# Calls swap_LineString.
return list(
swap_LineString(ring_coords) for ring_coords in coords)
# The next function is applied to each record in the following
# processing code.
def swap(rec):
"""Returns a record after swapping its geometry's coordinate x,y."""
# Use lexical dispatch on geometry type to get the proper translation
# function.
handlers = {
'Point': swap_Point,
'LineString': swap_LineString,
'Polygon': swap_Polygon }
g = rec['geometry']
g['coordinates'] = handlers[g['type']](g['coordinates'])
rec['geometry'] = g
return rec
except Exception, e:
log.exception("Error processing record %s:", rec)
def draw(axes, rec):
"""Given matplotlib axes and a record, adds the record as a patch
and returns the axes so that reduce() can accumulate more
PolygonPatch(rec['geometry'], fc=BLUE, ec=BLUE, alpha=0.5, zorder=2))
return axes
if __name__ = "__main__":
# Set up the figure and axes.
figure = pyplot.figure(1, figsize=(6, 6), dpi=90)
axes = figure.add_subplot(111)
with collection("docs/data/test_uk.shp", "r") as source:
results = imap(swap, source)
reduce(draw, results, axes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.