Creating Geographically Bounded Maps with Cartopy

  • Share this:

Code introduction


This function uses the Cartopy library to create a map and draw features such as national borders and coastlines within a specified geographic boundary.


Technology Stack : Cartopy, NumPy, Matplotlib

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np

def plot_map_with_borders(lng_min, lng_max, lat_min, lat_max):
    """
    This function creates a map with specified geographic boundaries and plots the borders.
    """
    # Create a map projection
    proj = ccrs.PlateCarree()
    
    # Create a figure and an axis
    fig, ax = plt.subplots(subplot_kw={'projection': proj})
    
    # Set the geographic boundaries of the map
    ax.set_extent([lng_min, lng_max, lat_min, lat_max])
    
    # Add land and ocean features
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)
    
    # Add national borders
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    
    # Add coastlines
    ax.add_feature(cfeature.COASTLINE)
    
    # Show the map
    plt.show()