我正在使用python matplotlib从温度数据的2D数组(存储在NetCDF文件中)生成等高线图,我有兴趣将轮廓多边形和/或线导出为geojson格式,以便我可以使用它们在matplotlib之外。我已经发现“pyplot.contourf”函数返回一个“QuadContourSet”对象,该对象具有包含轮廓坐标的“collections”属性:
contourSet = plt.contourf(data, levels)
collections = contourSet.collections
有没有人知道matplotlib是否有办法将“集合”中的坐标导出为各种格式,特别是geojson?我搜索了matplotlib文档和网页,但没有提出任何明显的内容。
谢谢!
答案 0 :(得分:4)
geojsoncontour是一个Python模块,可将matplotlib等高线转换为geojson。
它使用以下简化但完整的方法将matplotlib轮廓转换为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)
答案 1 :(得分:2)
确保导出所有轮廓的良好开端是在迭代get_paths
个对象然后Collection
to_polygons
方法时使用Path
方法得到numpy数组:
http://matplotlib.org/api/path_api.html?highlight=to_polygons#matplotlib.path.Path.to_polygons
然而,最终格式取决于你。
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