如何使用Cartopy将自定义Shapefile添加到地图中

7

使用basemap,我曾经这样添加我的自定义边界shapefile:

map = Basemap(..)
map.readshapefile(file.shp, 'attribute', drawbounds=True)

我该如何用Cartopy实现同样的效果?

我尝试了以下代码:

ax.add_feature(cfeature.shapereader.Polygon('file.shp'))

但是那不起作用了。
1个回答

18

目前没有ShapefileFeature类(虽然很容易创建,而且可能非常有意义),因此如果你真的想使用要素接口,就需要跳过一个障碍:

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

fname = '50m_glaciated_areas.shp'

ax = plt.axes(projection=ccrs.Robinson())
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                                ccrs.PlateCarree(), facecolor='none')
ax.add_feature(shape_feature)
plt.show()

或者,您可以使用add_geometries方法,该方法不使用特征界面(因此在未来,将不会针对仅从磁盘读取实际绘制的几何图形这种情况进行优化,就像ShapefileFeature类一样):

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

fname = '50m_glaciated_areas.shp'

ax = plt.axes(projection=ccrs.Robinson())
ax.add_geometries(Reader(fname).geometries(),
                  ccrs.PlateCarree(),
                  facecolor='white', hatch='xxxx')
plt.show()

带斑点的冰川区域

祝一切顺利


谢谢,这感觉就像是正确地完成了它,而不是用我的形状文件替换文件夹中的:C:\Users\lenovo.local\share\cartopy\shapefiles\natural_earth\physical;) - Mattijn
确实是这样!很高兴你有比那更好的解决方案 :) - pelson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接