Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 57 ยท 3D, Animation and Advanced

Maps with Matplotlib, GeoPandas and Cartopy

Draw maps in Python: longitude and latitude as x and y, fixing map distortion, projections, choropleth maps with polygons, GeoPandas, and Cartopy for real coastlines.

A map is a scatter plot or a set of polygons whose coordinates happen to be places on Earth. Everything you already know about Matplotlib applies: Axes, colour maps, annotations, legends. What is new is that the Earth is round and paper is flat, so maps need coordinate systems and projections, and special care that shapes are not squashed.

This lesson starts with pure Matplotlib, so you understand what a map is made of, then shows GeoPandas for real geographic data frames. Cartopy, the third library, needs downloaded map files and cannot run in the browser, so its code is read-only. To keep everything original and self-contained, the map data here is a fictional archipelago that we define ourselves. With real files the code is identical; only the source of the polygons changes.

Longitude and latitude are just x and y

Positions on Earth are given as longitude (east-west, -180 to 180 degrees) and latitude (north-south, -90 to 90). If you plot longitude on x and latitude on y, you get the simplest map projection, called equirectangular or plate carree. Here are the islands of our imaginary Veria archipelago, drawn as polygons with ax.fill:

Python Polygons in longitude and latitude

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

zip(*corners) turns a list of (lon, lat) pairs into two sequences, a longitude list and a latitude list, which is exactly what ax.fill wants. Compare this with the shapes: do they look right? Not quite, and the next section shows why.

Keep the aspect ratio honest

One degree of latitude is always about 111 km. But one degree of longitude gets shorter as you move away from the equator: it is about 111 km times the cosine of the latitude. At latitude 51 degrees north it is only about 70 km. If x and y use the same scale per degree, a map at that latitude looks too wide.

A simple fix for small areas is to set the aspect ratio to 1 / cos(latitude):

Python Correcting the aspect ratio

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The block is 4 degrees wide and 4 degrees high, but in kilometres it is only about 280 km wide and 444 km high. The right panel shows the true proportions. This trick is fine for a country or a region. For continents or the whole world you need a real projection.

Projections: flattening a sphere

Flattening a sphere always distorts something: area, shape, distance or direction. Every projection chooses what to keep.

Projection Keeps Distorts
Equirectangular (plate carree) Simple grid Shapes and areas away from the equator
Mercator Local shapes and compass directions Area grows hugely toward the poles
Mollweide, Hammer Area (equal-area) Shapes near the edges
Orthographic Looks like a globe from space Only one hemisphere shown

Matplotlib has built-in projections "mollweide", "hammer", "aitoff" and "lambert", which take longitude and latitude in radians. You can also write a projection as a formula. Mercator's formulas are x = lon and y = ln(tan(pi/4 + lat/2)):

Python Equirectangular, Mercator and Mollweide compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the Mercator panel the parallels spread further apart toward the top and bottom; that stretching is why Greenland looks as large as Africa on Mercator maps. The Mollweide panel squeezes meridians toward the poles and keeps areas true, which is why it is popular for global data. Choose the projection for the message: Mercator for navigation and web tiles, an equal-area projection for comparing sizes or densities.

Choropleth maps: colour regions by a value

A choropleth colours each region by a number, such as population density. With plain Matplotlib you draw each polygon as a Polygon patch, collect them in a PatchCollection and attach a colour map. The collection takes an array of values and colours the polygons for you:

Python A choropleth from polygons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two reminders from Design Principles matter even more on maps. First, use a sequential colour map for a quantity that goes from low to high. Second, colour by rates or densities, not raw totals: big regions tend to have big totals, so a map of totals mostly shows where the big regions are.

Distances on a sphere

Straight-line distance on a flat map is wrong for places far apart. The haversine formula gives the great-circle distance, the shortest path along the surface, and it takes four lines of NumPy:

Python Great-circle distance with NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The column vector lon[:, None] against the row vector lon[None, :] builds the whole distance table with broadcasting, no loops needed.

GeoPandas: geographic data frames

Real map data comes in files such as shapefiles, GeoJSON and GeoPackage. GeoPandas reads them into a GeoDataFrame: a pandas DataFrame with a geometry column that holds polygons, lines or points (using the Shapely library), plus a CRS (coordinate reference system) that says what the numbers mean. gdf.plot(column="density") draws a choropleth in one line and returns a Matplotlib Axes.

Python A GeoDataFrame choropleth

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

GeoPandas loads several big libraries, so the first run in the browser can take half a minute while they download; later runs are quick. Remember two rules. Always check gdf.crs, because longitude/latitude (EPSG:4326) are degrees, and areas or distances calculated in degrees are meaningless. And project before measuring: call to_crs with a suitable metre-based CRS (above, an equal-area projection for Europe) and then use .area, .length or .distance.

Real coastlines with Cartopy

For the real world, Cartopy adds map-aware Axes. You choose a projection when you create the Axes, add natural-earth coastlines and borders, and plot your data in longitude and latitude by telling Cartopy which coordinate system your numbers use. This code is read-only here, because Cartopy needs to download map files and uses libraries that are not available in the browser:

Python
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 4))
ax = plt.axes(projection=ccrs.Robinson())          # how the map is drawn
ax.set_global()
ax.add_feature(cfeature.LAND, facecolor="#e5e7eb")
ax.add_feature(cfeature.COASTLINE, linewidth=0.5)
ax.gridlines(draw_labels=False, alpha=0.4)

# Points are given in lon/lat, so say so with transform=
ax.scatter([2.35, -74.0, 139.7], [48.86, 40.7, 35.7],
           transform=ccrs.PlateCarree(), color="tab:red", zorder=5)
ax.set_title("Cartopy: Robinson projection")
plt.show()

The key idea is the pair projection / transform: projection= is how the map looks, and transform= is the system your data is in. Forgetting transform=ccrs.PlateCarree() is the most common Cartopy mistake: points then land in strange places. Other tools worth knowing are Plotly maps and Folium for interactive tile maps, and contextily for adding background street maps beneath GeoPandas plots.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does an equirectangular map at 60 degrees north look too wide?

    Meridians converge toward the poles, so one degree of longitude covers less distance as latitude grows. Setting the aspect to 1 / cos(latitude) compensates for small regions.
  2. 2. Which projection should you choose to compare the areas of countries?

    Equal-area projections keep areas true, though shapes distort. Mercator exaggerates areas near the poles.
  3. 3. What should a choropleth usually show?

    Totals mostly reflect region size. Rates or densities allow fair comparison, and sequential colours show low-to-high order.
  4. 4. In GeoPandas, why call to_crs() with a projected CRS before using .area?

    EPSG:4326 coordinates are degrees. Areas and distances need a metre-based projected coordinate system.
  5. 5. In Cartopy, what is transform=ccrs.PlateCarree() for?

    projection= sets how the map is drawn; transform= declares the coordinate system of the data you plot on it.

Summary

  • A map is a plot of longitude (x) and latitude (y); polygons are drawn with ax.fill, Polygon patches or a PatchCollection.
  • Fix the aspect ratio for regional maps with ax.set_aspect(1 / np.cos(np.radians(lat))); use a real projection for large areas.
  • Every projection distorts something: Mercator keeps local shape, Mollweide keeps area.
  • Choropleths colour regions by rates or densities with a sequential colour map; use set_array on a collection.
  • Haversine plus broadcasting gives great-circle distances.
  • GeoPandas pairs pandas with geometry and a CRS: check gdf.crs, project with to_crs before measuring. Cartopy (read-only here) separates projection from transform.

Next: Animation Concepts adds time to your plots.