How to add a point-feature shapefile to map using cartopy

我与影子孤独终老i 提交于 2019-12-21 04:54:15

问题


I have two shapefiles. One is a point feature shapefile, named "point.shp", the other is a polygon shapefile named "polygon.shp". Both I want to add to a map using cartopy. I managed to add the "polygon.shp", but failed with the "point.shp".

Here's my code:

import matplotlib.pyplot as plt
from cartopy import crs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

ax = plt.axes(projection=crs.PlateCarree())

# add the polygon file, worked
ax.add_geometries(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='w')

# or(also worked):
ax.add_feature(ShapelyFeature(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='r'))

# but these two ways both failed with the "point.shp"
ax.add_geometries(Reader("point.shp").geometries(), crs.PlateCarree())

# or, this doesn't work neither:
ax.add_feature(ShapelyFeature(Reader("polygon.shp").geometries(), crs.PlateCarree(), facecolor='r'))

Does any one know how to do this, or why, without retrieving all the points' x, y coords and then plotting them?

And with coordinates(x, y values), ax.plot() works, but ax.scatter() fails, why?

Thanks


回答1:


add_geometries currently turns a geometry into a polygon and then colours it appropriately, which of course means that when you pass points the add_geometries, the polygons are not visible. Potentially cartopy could do a better job of this in the future, but in the meantime, it sounds like you just want to use something like scatter to visualize your data.

You can achieve this by getting the x and y coordinate values out of the geometry and passing these straight on to scatter with the appropriate transform:

import cartopy.crs as ccrs
import cartopy.io
import matplotlib.pyplot as plt


fname = cartopy.io.shapereader.natural_earth(resolution='10m',
                                               category='cultural',
                                               name='populated_places_simple')

plt.figure(figsize=(12, 6))
ax = plt.axes(projection=ccrs.Robinson())

ax.set_title('Populated places of the world.')
ax.coastlines()

points = list(cartopy.io.shapereader.Reader(fname).geometries())

ax.scatter([point.x for point in points],
           [point.y for point in points],
           transform=ccrs.Geodetic())

plt.show()

HTH



来源:https://stackoverflow.com/questions/25340427/how-to-add-a-point-feature-shapefile-to-map-using-cartopy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!