Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib contour plot geojson output?

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!

like image 832
embeepea Avatar asked Sep 06 '25 03:09

embeepea


1 Answers

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)
like image 52
Bart Römgens Avatar answered Sep 08 '25 10:09

Bart Römgens