Creating a Cartopy Map with Coastlines, Borders, and Grid

  • Share this:

Code introduction


This function creates a map using the Cartopy library and adds coastlines, borders, and a grid.


Technology Stack : Cartopy, Numpy

Code Type : Map drawing

Code Difficulty : Intermediate


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

def plot_map_with_borders_and_grid(arg1, arg2):
    # Create a figure and an axes with Cartopy's projection
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    
    # Add coastlines and borders to the map
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    
    # Create a grid and add it to the map
    m = ccrs.Mercator()
    x, y = np.meshgrid(np.linspace(-180, 180, arg1), np.linspace(-90, 90, arg2))
    grid = m.transform_points(ccrs.PlateCarree(), x, y)
    ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
    
    # Set the extent of the map
    ax.set_extent([0, 360, -90, 90], crs=ccrs.PlateCarree())
    
    # Show the plot
    plt.show()                
              
Tags: