Plotting Maps with Cartopy and Features

  • Share this:

Code introduction


This function uses the Cartopy library to plot a map and adds features such as coastlines, land, oceans, and state boundaries. It also allows for plotting specified longitude and latitude points on the map.


Technology Stack : Cartopy, Numpy, Matplotlib

Code Type : Map drawing

Code Difficulty : Intermediate


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

def plot_map_with_features(lon, lat, projection=ccrs.PlateCarree()):
    """
    Plots a map with specified longitude and latitude coordinates and features.
    """
    fig, ax = plt.subplots(subplot_kw={'projection': projection})
    
    # Add coastlines
    ax.add_feature(cfeature.COASTLINE)
    
    # Add land
    ax.add_feature(cfeature.LAND)
    
    # Add oceans
    ax.add_feature(cfeature.OCEAN)
    
    # Add states
    ax.add_feature(cfeature.STATES)
    
    # Plot points
    scatter = ax.scatter(lon, lat, transform=ccrs.PlateCarree())
    
    # Set title
    ax.set_title('Map with Features')
    
    plt.show()