I have a code like this:
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()
This produces the following image:
The line I have a problem with is ax1.set_extent((2, 52, -40, 10))
. Is there a way, I could get a country's extent rather than putting it in manually? In all the documentation, I always see people hardcoding the tuple but that's infeasible when cycling through the whole dataset of countries.
From a country's geometry, you can get its bounds. From the bounds, you can grab the limits like this:
lon_min, lat_min, lon_max, lat_max = acountry.geometry.bounds
The extent can be set using the obtained values:
ax1.set_extent((lon_min, lon_max, lat_min, lat_max))