Cartopy Map Plotting with Geographic Features

  • Share this:

Code introduction


This function uses the Cartopy library to plot maps and add specified geographic features such as coastlines, borders, lakes, and natural earth features. The function takes two parameters: the name of the feature to be added to the map and the coordinate reference system (CRS) to use for the plot.


Technology Stack : Cartopy, NumPy, matplotlib.pyplot

Code Type : Geographic Information System (GIS) Programming

Code Difficulty : Intermediate


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

def plot_map_with_features(arg1, arg2):
    """
    This function plots a map with specified geographic features using Cartopy.
    :param arg1: The name of the feature to be plotted on the map.
    :param arg2: The coordinate reference system (CRS) to use for the plot.
    """
    fig, ax = plt.subplots(subplot_kw={'projection': arg2})
    
    # Adding geographic features to the map
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5)
    
    # Plotting the specified feature
    ax.add_feature(cfeature.NATURAL_EARTH, name=arg1)
    
    # Setting map limits
    ax.set_extent([0, 10, 0, 10], crs=arg2)
    
    # Displaying the map
    plt.show()