Plot World Map with Specified Longitude Range Using Cartopy

  • Share this:

Code introduction


This function uses the Cartopy library to plot a world map with country boundaries. Users can specify the longitude range of the map.


Technology Stack : Cartopy, NumPy, Matplotlib

Code Type : Function

Code Difficulty : Intermediate


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

def plot_world_map_with_countries(arg1, arg2):
    # Create a figure and an axis.
    fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})

    # Add countries as feature to the map.
    ax.add_feature(cfeature.COUNTRIES, edgecolor='black', facecolor='none')

    # Set the limits of the map.
    ax.set_extent([arg1, arg2, -90, 90], crs=ccrs.PlateCarree())

    # Plot a grid on the map.
    gl = ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
    gl.xlabels_top = False
    gl.ylabels_right = False

    # Display the map.
    plt.show()