Draw World Map with Grid Lines using Cartopy

  • Share this:

Code introduction


This function draws a world map with grid lines using the Cartopy library. It takes latitude and longitude arrays as arguments and marks these points on the map.


Technology Stack : Cartopy, Numpy, Matplotlib

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(lats, lons):
    """
    This function draws a map with grid lines using Cartopy library.
    """
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    ax.set_global()
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')

    # Create grid lines
    m = ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
    m.xlabels_top = False
    m.ylabels_right = False

    # Add lats and lons to the map
    ax.scatter(lons, lats, transform=ccrs.PlateCarree(), color='red')
    ax.set_title('Map with Grid Lines')

    plt.show()

# Example usage
lats = np.linspace(-90, 90, 10)
lons = np.linspace(-180, 180, 10)
draw_map_with_grid(lats, lons)