如何使用 Natural Earth 数据和 Cartopy 获取国家的边界框
在此示例中,我们将使用公共领域的 Natural Earth 数据集和 Cartopy 库确定肯尼亚的边界框。
仅渲染肯尼亚的边界框(实际国家以绿色高亮显示)看起来像这样:
如何获取边界框
首先我们使用 Cartopy 的 cartopy.io.shapereader.natural_earth() 函数,它将自动下载 Natural Earth 数据(如果已下载,将使用缓存数据):
kenya_bbox_reader.py
shpfilename = shpreader.natural_earth(resolution='10m',
category='cultural',
name='admin_0_countries')
reader = shpreader.Reader(shpfilename)现在我们可以像我们在之前关于如何使用 Cartopy 高亮特定国家的文章中所做的那样筛选肯尼亚:
kenya_bbox_select.py
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]并使用 kenya.bounds 获取边界框:
kenya_bbox_bounds.py
lon_min, lat_min, lon_max, lat_max = kenya.bounds完整示例代码
此代码将渲染上面显示的图像:
kenya_bbox_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)
import cartopy.io.shapereader as shpreader
# 读取 shape 文件
shpfilename = shpreader.natural_earth(resolution='10m',
category='cultural',
name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
# 筛选特定国家
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]
# 确定边界框
lon_min, lat_min, lon_max, lat_max = kenya.bounds
ax.set_extent([lon_min, lon_max, lat_min, lat_max])
# 显示肯尼亚的形状
shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
ax.add_feature(shape_feature)
# 将图保存为 SVG
plt.savefig("Kenya-Bounding-Box-Tight.svg")If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow