Plotting Maps with Gridlines and Scatter Points Using Cartopy

  • Share this:

Code introduction


This function uses the Cartopy library to plot a map and adds gridlines and scatter plots. By providing longitude and latitude arrays, specific data points can be displayed on the map.


Technology Stack : Cartopy, Numpy, Matplotlib

Code Type : Map drawing

Code Difficulty : Intermediate


                
                    
import cartopy.crs as ccrs
import numpy as np
import matplotlib.pyplot as plt

def plot_map_with_gridlines(lons, lats):
    """
    This function plots a map with specified longitude and latitude arrays, and adds gridlines.
    """
    # Create a figure and an axes with Cartopy's projection
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    
    # Draw the map
    ax.drawmapboundary()
    
    # Draw gridlines
    gl = ax.gridlines(draw_labels=True, dms=True)
    gl.xlabels_top = False
    gl.ylabels_right = False
    
    # Scatter plot for longitude and latitude points
    scatter = ax.scatter(lons, lats, transform=ccrs.PlateCarree(), color='blue', zorder=5)
    
    # Add a colorbar
    cbar = plt.colorbar(scatter, orientation='horizontal', pad=0.05, aspect=50)
    cbar.set_label('Data Points')
    
    # Set title and labels
    ax.set_title('Map with Gridlines and Scatter Points')
    ax.set_xlabel('Longitude')
    ax.set_ylabel('Latitude')
    
    # Show the plot
    plt.show()

# Example usage
lons = np.random.uniform(-180, 180, 100)
lats = np.random.uniform(-90, 90, 100)

plot_map_with_gridlines(lons, lats)