Cartopy-based Contour Map Plotting with Cartopy and Features

  • Share this:

Code introduction


This function uses the Cartopy library to plot a contour map on given latitude and longitude data, and adds coastlines, borders, and gridlines.


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 plot_contour_map(latitudes, longitudes, data):
    """
    Plots a contour map using Cartopy with given latitude and longitude data and contour levels.
    """
    # Create a figure and an axes in this figure with Cartopy's projection
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
    
    # Generate a grid of latitude and longitude values
    x, y = np.meshgrid(longitudes, latitudes)
    
    # Plot the contour map
    cont = ax.contourf(x, y, data, levels=10, cmap='viridis')
    
    # Add coastlines, borders and gridlines
    ax.coastlines()
    ax.add_feature(cfeature.BORDERS)
    ax.gridlines(draw_labels=True)
    
    # Add a colorbar
    fig.colorbar(cont)
    
    # Show the plot
    plt.show()

# Example usage:
# latitudes = np.linspace(-90, 90, 100)
# longitudes = np.linspace(-180, 180, 100)
# data = np.random.rand(100, 100)
# plot_contour_map(latitudes, longitudes, data)