Cartopy Map with Grid and Features

  • Share this:

Code introduction


This function uses the Cartopy library to draw a map with grid, coastlines, land, oceans, lakes, and borders.


Technology Stack : Cartopy, NumPy

Code Type : Function

Code Difficulty : Intermediate


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

def draw_map_with_grid(ax, proj):
    """
    This function draws a map with grid using Cartopy library.
    """
    # Add grid to the map
    ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
    
    # Add coastlines to the map
    ax.add_feature(cfeature.COASTLINE)
    
    # Add land to the map
    ax.add_feature(cfeature.LAND)
    
    # Add oceans to the map
    ax.add_feature(cfeature.OCEAN)
    
    # Add lakes to the map
    ax.add_feature(cfeature.LAKES)
    
    # Add borders to the map
    ax.add_feature(cfeature.BORDERS)

# Usage example
fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
draw_map_with_grid(ax, ccrs.PlateCarree())                
              
Tags: