首页 > 解决方案 > Cartopy - 手动 set_extent

问题描述

我有这样的代码:

shpfilename = shpreader.natural_earth(resolution='110m',
                                          category='cultural',
                                          name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
    
countries = reader.records()
country = list(countries)[25]

central_lon, central_lat = 20, 0
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1,projection=ccrs.PlateCarree())
ax2 = fig.add_subplot(1,2,2, projection=ccrs.Orthographic(central_lon, central_lat))

fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

s = cfeature.AdaptiveScaler('coarse',(('intermediate', 30), ('fine', 10)))

ax1.set_extent((2, 52, -40, 10))
ax1.coastlines(resolution='50m')
ax1.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
ax1.add_feature(cartopy.feature.LAND,facecolor=np.array((240, 240, 220)) / 256.)
ax1.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(0, 0, 1))

ax2.gridlines()
ax2.add_feature(cartopy.feature.LAND,facecolor=np.array((240, 240, 220)) / 256.)
ax2.add_feature(cartopy.feature.OCEAN) ax2.add_geometries(country.geometry,ccrs.PlateCarree(),facecolor=(0, 0, 1))
ax2.coastlines(resolution='50m')

plt.savefig("cartopy/{}.png".format("img1"))
plt.show()

这将产生以下图像:

地图.

我有问题的行是ax1.set_extent((2, 52, -40, 10)). 有没有办法,我可以得到一个国家的范围而不是手动输入?在所有文档中,我总是看到人们对元组进行硬编码,但是在遍历整个国家数据集时这是不可行的。

标签: python-3.xcartopy

解决方案


从一个国家的几何形状,你可以得到它的界限。从边界,您可以像这样抓住限制:

lon_min, lat_min, lon_max, lat_max = acountry.geometry.bounds

可以使用获得的值设置范围:

ax1.set_extent((lon_min, lon_max, lat_min, lat_max))

推荐阅读