如何使用 Cartopy 高亮特定国家

在我们之前的文章中,例如如何使用 Cartopy 绘制非洲地图,我们展示了如何使用 Cartopy 绘制整个大洲的概览地图。这篇文章提供了如何在该地图中高亮特定国家的示例。在此示例中,我们将高亮肯尼亚

使用 Cartopy 以酸橙绿色高亮肯尼亚的非洲地图一般方法是:

  1. 使用 cartopy.io.shapereader.natural_earth 下载包含肯尼亚形状的 Natural Earth 数据
  2. 将其转换为 cartopy.feature.ShapelyFeature
  3. 显示该特征

在 cartopy 中显示肯尼亚的 Natural Earth 形状

首先,我们为 Natural Earth 数据创建一个 Reader。如果数据尚未缓存,Cartopy 将自动下载它。

highlight_kenya_reader.py
import cartopy.io.shapereader as shpreader

shpfilename = shpreader.natural_earth(resolution='110m',
                                      category='cultural',
                                      name='admin_0_countries')
reader = shpreader.Reader(shpfilename)

现在我们可以按名称从记录中选择肯尼亚:

highlight_kenya_select.py
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]

为了显示该几何图形,我们使用

highlight_kenya_draw.py
shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
ax.add_feature(shape_feature)

完整示例代码

highlight_kenya_complete.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)

# 读取 Natural Earth 数据
import cartopy.io.shapereader as shpreader

shpfilename = shpreader.natural_earth(resolution='110m',
                                      category='cultural',
                                      name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
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