World maps in Python - free map resources

Map files (ZIP): 

Natural Earth - Free vector and raster map data at 1:10m, 1:50m, and 1:110m scales (naturalearthdata.com)

The code below uses "Admin 0 – Countries" although other map files should also work, if they have countries in their 'NAME' column.


Python:

Installing packages [geopandas] [seaborn]:

 

pip install geopandas seaborn


Loading the world map:


import geopandas as gpd

# load the low resolution world map

world = gpd.read_file("./resources/ne_110m_admin_0_countries.zip") # ref https://www.naturalearthdata.com/downloads/110m-cultural-vectors/

all_countries = world['NAME']


def prepare_world_map_countries(country_names_to_highlight):

    countries_joined = '|'.join(country_names_to_highlight))

    countries_joined


    countries = world[world['NAME'].str.contains(countries_joined) == True]

    countries = list(countries['NAME'])

    return countries


Plotting the world map:


import matplotlib.patches as mpatches

import seaborn as sns


def plot_world_map(countries, title):

    # initialize a new figure

    fig = plt.figure(figsize=(20, 10))

    ax = fig.add_subplot()


    colors = sns.color_palette("husl", len(all_countries))

    patches = []


    # loop over the continent names and corresponding colors

    for (country_name, color) in list(zip(all_countries, colors)):

        # grab all countries that belong to the continent, then plot each of the

        # continents, giving each a unique color

        continent = world[world["NAME"] == country_name]

        is_active_country = country_name in countries

        actual_color = color if is_active_country else 'white'

        continent.plot(ax=ax, color=actual_color, edgecolor="black", alpha=0.5)


        # generate a patch for the current continent

        patch = mpatches.Patch(label=country_name, color=color)

        if is_active_country:

            patches.append(patch)


    # add the patches to the map

    ax.legend(handles=patches, loc="lower left", ncol=4)


    # turn off axis ticks

    ax.set_xticks([])

    ax.set_yticks([])


    # set the plot title

    plt.title(title)

    plt.show()


Example execution:

country_names_to_highlight = ['United States of America',

 'South Africa',

 'Brazil',

     'China',

     'Australia', 

 'Colombia',

 'France']

plot_world_map(country_names_to_highlight, "Countries Visited")

Resulting map:




Comments