如何在 Cartopy 中绘制 Shapefile 数据

为了在 Cartopy 中显示 shapefile 数据,我们可以首先使用 cartopy.io.shapereader 包读取 shape 数据,然后将我们要显示的几何图形转换为 cartopy.feature.ShapelyFeature

在以下示例中,我们将读取 Natural Earth ne_110m_admin_0_countries.shp注意有一种更简单的方法使用 shpreader.natural_earth 绘制 Natural Earth 数据 - 请参见如何使用 Cartopy 高亮特定国家,我们将仅以 Natural Earth 数据集为例!

how-to-plot-shapefile-data-in-cartopy.py
import cartopy.io.shapereader as shpreader
# 读取 shape 文件
reader = shpreader.Reader("ne_110m_admin_0_countries.shp")
# 筛选特定国家
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]

# 显示肯尼亚的形状
shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
ax.add_feature(shape_feature)

完整代码示例

cartopy_shapefile_complete_example.py
import cartopy.crs as ccrs
import cartopy.feature as cf
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt

proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)
# 仅显示非洲
ax.set_extent([-23, 55, -35, 40])
ax.stock_img()

ax.add_feature(cf.COASTLINE, lw=2)
# 使图更大
plt.gcf().set_size_inches(20, 10)

import cartopy.io.shapereader as shpreader
# 读取 shape 文件
reader = shpreader.Reader("ne_110m_admin_0_countries.shp")
# 筛选特定国家
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]

# 显示肯尼亚的形状
shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
ax.add_feature(shape_feature)

# 将图保存为 SVG
plt.savefig("Africa-Highlight-Kenya.svg")

Check out similar posts by category: Cartopy, Geography, Python