3
votes

I'm using python matplotlib to generate contour plots from an 2D array of temperature data (stored in a NetCDF file), and I am interested in exporting the contour polygons and/or lines into geojson format so that I can use them outside of matplotlib. I have figured out that the "pyplot.contourf" function returns a "QuadContourSet" object which has a "collections" attribute that contains the coordinates of the contours:

contourSet = plt.contourf(data, levels)
collections = contourSet.collections

Does anyone know if matplotlib has a way to export the coordinates in "collections" to various formats, in particular geojson? I've searched the matplotlib documentation, and the web, and haven't come up with anything obvious.

Thanks!

2
I think you're gonna have to write your own exporter :/ (you should definitely share it with the MPL community if you do) - Paul H

2 Answers

4
votes

geojsoncontour is a Python module that converts matplotlib contour lines to geojson.

It uses the following, simplified but complete, method to convert a matplotlib contour to geojson:

import numpy
from matplotlib.colors import rgb2hex
import matplotlib.pyplot as plt
from geojson import Feature, LineString, FeatureCollection

grid_size = 1.0
latrange = numpy.arange(-90.0, 90.0, grid_size)
lonrange = numpy.arange(-180.0, 180.0, grid_size)
X, Y = numpy.meshgrid(lonrange, latrange)
Z = numpy.sqrt(X * X + Y * Y)

figure = plt.figure()
ax = figure.add_subplot(111)
contour = ax.contour(lonrange, latrange, Z, levels=numpy.linspace(start=0, stop=100, num=10), cmap=plt.cm.jet)

line_features = []
for collection in contour.collections:
    paths = collection.get_paths()
    color = collection.get_edgecolor()
    for path in paths:
        v = path.vertices
        coordinates = []
        for i in range(len(v)):
            lat = v[i][0]
            lon = v[i][1]
            coordinates.append((lat, lon))
        line = LineString(coordinates)
        properties = {
            "stroke-width": 3,
            "stroke": rgb2hex(color[0]),
        }
        line_features.append(Feature(geometry=line, properties=properties))

feature_collection = FeatureCollection(line_features)
geojson_dump = geojson.dumps(feature_collection, sort_keys=True)
with open('out.geojson', 'w') as fileout:
    fileout.write(geojson_dump)
2
votes

A good start to be sure to export all contours is to use the get_paths method when you iterate over the Collection objects and then the to_polygons method of Path to get numpy arrays:

http://matplotlib.org/api/path_api.html?highlight=to_polygons#matplotlib.path.Path.to_polygons.

Nevertheless the final formatting is up to you.

import matplotlib.pyplot as plt
cs = plt.contourf(data, levels)
for collection in cs.collections:
    for path in collection.get_paths():
        for polygon in path.to_polygons(): 
            print polygon.__class__
            print polygon