Creating a World Map with Features and Random Points

  • Share this:

Code introduction


This code defines a function to draw a world map, including coastlines, borders, land, gridlines, and shaded relief. It also randomly marks 10 red points on the map.


Technology Stack : Cartopy, NumPy, Matplotlib

Code Type : Map drawing

Code Difficulty : Intermediate


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

def plot_world_map_with_features():
    # Set up the map projection.
    ax = plt.axes(projection=ccrs.PlateCarree())
    
    # Add coastlines, borders, and land.
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS)
    ax.add_feature(cfeature.LAND)
    
    # Add gridlines.
    ax.gridlines(draw_labels=True)
    
    # Create a color map and set the extent.
    cmap = plt.get_cmap('Blues')
    ax.add_collection(cfeature.NATURAL_EARTH.shadedrelief(scale='110m'))
    
    # Generate random points on the map.
    random_points = np.random.rand(10, 2) * 360 - 180
    for point in random_points:
        lon, lat = point
        ax.plot(lon, lat, marker='o', color='red', markersize=5, transform=ccrs.PlateCarree())
    
    plt.show()