Matplotlib Tutorial: Let’s Take Your Country Maps to Another Level | by Oscar Leo | Sep, 2023


Matplotlib Tutorial

How to draw beautiful maps with Python and Matplotlib

Oscar Leo
Towards Data Science
Map created by the author

Yes, I created the map above using Matplotlib, and I’ll show you how in this tutorial.

The idea is to create a reusable and flexible function that allows me to instantly draw a beautiful map of any area.

With such a function, I can save a ton of time when I want to create charts or infographics with a geographical component.

I also want to show the power of reusable code since many programmers working with data visualization forget about such best practices.

This tutorial contains every single line of code you need to create the map of Africa above.

Let’s get started.

Step 1: Download geo data

The only thing you need to do before you can start the tutorial is to download geo data from here:

World Boundaries GeoJSON — Very High Resolution

It’s the official boundaries from the World Bank and a public dataset you can use however you want.

Step 2: Import libraries

As usual, we start by importing the necessary libraries, and we don’t need many. Since we have geographical data, we want geopandas to make plotting as easy as possible.

import numpy as np
import pandas as pd
import seaborn as sns
import geopandas as gpd
import matplotlib.pyplot as plt

import matplotlib.patheffects as PathEffects
from matplotlib.patches import Polygon

One import that you might have yet to see is PathEffe. I will use that to create a border around the country labels later.

Step 3: Create a seaborn style

Before plotting, I always create a seaborn style to get a coherent look. Here, I only define a background_color, font_family, and text_color. I’m setting the background to light blue to represent the ocean.

font_family = "sans"
background_color = "#D4F1F4"
text_color = "#040303"

sns.set_style({
"axes.facecolor": background_color…



Source link

This post originally appeared on TechToday.