Random Data Grid Map Generation with Cartopy

  • Share this:

Code introduction


This function generates a map with a grid of random data using the Cartopy library. It takes two arguments, representing the number of grid points for longitude and latitude.


Technology Stack : Cartopy, NumPy

Code Type : Map generation

Code Difficulty : Intermediate


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

def generate_random_grid_map(arg1, arg2):
    # Create a figure and an axes with Cartopy's projection
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    
    # Generate random data
    lon = np.linspace(-180, 180, arg1)
    lat = np.linspace(-90, 90, arg2)
    data = np.random.rand(arg1, arg2)
    
    # Create a grid from the data
    mesh = ax.pcolormesh(lon, lat, data, transform=ccrs.PlateCarree())
    
    # Add coastlines, borders, and gridlines
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.gridlines(draw_labels=True)
    
    # Set title
    ax.set_title('Random Grid Map')
    
    # Return the figure and axes
    return fig, ax                
              
Tags: