Plotting Maps with Borders and Coastlines using Cartopy

  • Share this:

Code introduction


This function uses the Cartopy library to plot a map with specified longitude and latitude boundaries, and adds borders and coastlines to the map.


Technology Stack : Cartopy, Matplotlib

Code Type : Cartop map rendering function

Code Difficulty : Intermediate


                
                    
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

def plot_map_with_borders_and_coastlines(lng_min, lng_max, lat_min, lat_max):
    """
    Plots a map with specified longitude and latitude boundaries, including borders and coastlines.
    """
    # Create a figure and an axis
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    
    # Set the map boundaries
    ax.set_extent([lng_min, lng_max, lat_min, lat_max])
    
    # Add borders and coastlines to the map
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.COASTLINE)
    
    # Display the map
    plt.show()