How to Make Colored Country Maps in Python (TLDR Edition)

Proto Bioengineering
2 min readNov 17, 2022

--

A quick how-to on turning a map of New Zealand into a “choropleth” map (i.e., a colored heatmap).

Choropleth maps of New Zealand’s police districts.

This is a TL;DR version of this article, which explains all of these steps, as well as maps and data wrangling, in more detail. Both of these articles have the same author.

Steps

import geopandas as gpd

map_dataframe = gpd.read_file('nz-police-district-boundaries.shx')
import pandas as pd

firearm_licenses = pd.read_file('nz_firearm_licenses.csv')
  • Combine the Geopandas and Pandas dataframes wherever their District columns match. The DISTRICT_N and Residence District columns are both 12 rows of names of New Zealand’s districts.
merged_dataframe = map_dataframe.merge(firearm_licenses, left_on=["DISTRICT_N"], right_on=["Residence District"])
  • Give the combined dataframe to Matplotlib to make the actual map.
merged_dataframe.plot(column="Licenses", cmap="Blues", legend=True)
  • Save the map as an image, and open it.
plt.savefig("nz_firearm_licenses.png", dpi=300)
plt.show()

Full Script

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

# Load New Zealand coordinates into Geopandas
map_dataframe = gpd.read_file("nz-police-district-boundaries.shx")

# Load firearm license data into Pandas
firearm_licenses = pd.read_csv("nz_firearm_licenses.csv")

# Combine both dataframes along their district columns
merged_dataframe = map_dataframe.merge(firearm_licenses, left_on=["DISTRICT_N"], right_on=["Residence District"])

# Create a Matplotlib plot/map with the combined dataframe. Use the "Licenses" column to decide colors.
merged_dataframe.plot(column="Licenses", cmap="Blues", legend=True)

# Save and show the map
plt.savefig("nz_firearm_licenses.png", dpi=300)
plt.show()

Result

The output of the above script that gets saved as a PNG on your computer.

How do I make my Matplotlib graphs look better?

Questions and Feedback

If you have questions or feedback, email us at protobioengineering@gmail.com or message us on Instagram (@protobioengineering).

If you liked this article, consider supporting us by donating a coffee.

Terms

Choropleth maps are colored maps of states, countries, etc. that show data.

Pandas is a Python library that helps you mess with data sets, like those in CSVs and Excel sheets.

Matplotlib is the most popular way to make graphs and charts in Python. Works well with Pandas.

Geopandas is Pandas with extra geographical/GIS functions added, which makes map-making easier.

shapefile — the file that has the coordinates for our map. It knows the shape of the states/provinces/countries/etc.

Further Reading

--

--

Proto Bioengineering

Learn to code for science. “Everything simple is false. Everything complex is unusable.” — Paul Valery