In our previous posts, e.g. How to draw Africa map using Cartopy we showed how to draw an overview map of an entire continent using Cartopy. This post provides an example of how to highlight a specific country in that map. In this example, we’ll highlight Kenya
- Use
cartopy.io.shapereader.natural_earth
to download Natural Earth data that contains the shape of Kenya - Convert it to a
cartopy.feature.ShapelyFeature
- Display said feature
Displaying Kenya’s Natural Earth shape in cartopy
First, we create a Reader
for the Natural Earth data. Cartopy will automatically download the data if it has not been cached.
import cartopy.io.shapereader as shpreader shpfilename = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries') reader = shpreader.Reader(shpfilename)
Now we can select Kenya by name from the records:
kenya = [country for country in reader.records() if country.attributes["NAME_LONG"] == "Kenya"][0]
In order to display that geometry, we use
shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1) ax.add_feature(shape_feature)
Complete example code
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) # Show only Africa ax.set_extent([-23, 55, -35, 40]) ax.stock_img() ax.add_feature(cf.COASTLINE, lw=2) # Make figure larger plt.gcf().set_size_inches(20, 10) # Read Natural Earth data 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] # Display Kenya's shape shape_feature = ShapelyFeature([kenya.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1) ax.add_feature(shape_feature) # Save figure as SVG plt.savefig("Africa-Highlight-Kenya.svg")