Geospatial Python

Mapping John Snow’s cholera outbreak

Jean Golding Institute

Housekeeping

  • Please keep your mic on mute unless you’re talking
  • Feel free to turn your camera on if you want to
  • We love questions! There’s no such thing as a silly question here
  • Don’t be afraid of error messages: they’re totally normal, and really helpful
  • We’ll take a break after 1 hour
  • If you need an extra break at any point, that’s okay: the session is recorded

How today works

Some theory. Then code it together.

  • Each section starts with the ideas behind it
  • Then we live code together: type along in your own copy of the notebook
  • Then a short exercise on your own, and the answer
  • Nothing to install: we use Google Colab, so you just need a Google account
  • The notes have all the code, exercises and answers: try each exercise before looking
  • We learn through one case study

Today’s mission

Can you find the source of a cholera outbreak, using a map?

Session overview

The story Soho, 1854 Cholera, two theories, and John Snow’s map

1 · Location data What do the numbers mean? Vector and raster data, GeoDataFrames and coordinate reference systems Exercise: where is pump 0?

2 · Making maps How do we show it? Layers, background maps and interactive maps Exercise: an interactive map

3 · The nearest pump Which pump was closest? Spatial relationships and spatial joins Exercise: deaths within 100 metres

4 · Pump catchments Which area did each pump serve? Voronoi polygons and choropleth maps Exercise: a map of catchments

5 · What the map cannot tell us Should we believe it? The evidence beyond the map, and the limits of areas Exercise: question the map

By the end, you will be able to

  1. Load location data into a GeoDataFrame, and describe how it differs from a pandas DataFrame
  2. Explain what a coordinate reference system (CRS) is, and check and change it
  3. Make a static map with a background map, and an interactive map
  4. Join datasets by location, for example to find the nearest pump to each address
  5. Divide an area into catchments around points, and summarise data within each one
  6. Describe what a map can and cannot tell us

00 The story

Soho, London, 1854

London in the 1850s

  • A fast-growing city, with families crowded into old houses
  • Sewage went into cesspits under and behind the houses
  • Many people fetched their water from street pumps
  • Cholera had already swept through Britain in the 1830s and 1840s

Black and white photograph of a run-down London courtyard, with people standing and sitting outside old brick houses

A London slum, 1860s. Wikimedia Commons

What is cholera?

  • A gut infection caused by the bacterium Vibrio cholerae
  • Spread through water and food contaminated with it
  • Causes acute watery diarrhoea, sometimes with vomiting
  • Untreated, severe dehydration can kill within hours
  • Today, most cases are treated with oral rehydration solution

A cartoon of cholera as a giant shrouded figure with skeletal hands and feet, trampling soldiers on a battlefield

Cholera “Tramples the victors & the vanquished both”, Robert Seymour, 1831. National Library of Medicine

Two theories

Miasma

Disease spreads through “bad air”, from rotting matter and filth. Most doctors believed this

Water

John Snow, a London physician, thought cholera spread through contaminated water

The two theories predict different patterns: bad air would spread across a neighbourhood, but water would cluster around its source

The Broad Street outbreak

30 Aug 1854
Outbreak starts
→ 1 Sep
143 fatal cases
→ Early Sep
Snow visits homes
→ 7 Sep
Evidence to parish
→ 8 Sep
Handle removed

  • Snow studied the death records, and asked households where they got their water
  • Most of the dead had lived near, and drunk from, the Broad Street pump

Snow’s map

John Snow's map of Soho, with each cholera death drawn as a small black bar stacked at its address, clustered around Broad Street

  • Each black bar is one death, stacked at the address
  • The pumps are marked on the map
  • Published in 1855, in the second edition of Snow’s On the Mode of Communication of Cholera

John Snow’s map. Wellcome Collection

The idea catches on

Cartoon of a skeleton working a street water pump, while poor women and children queue to fill jugs

Death’s Dispensary, from the magazine Fun, 1866: Death himself works the pump

Snow died in 1858. Within a decade, the link between dirty water and disease was a subject for cartoons

George J. Pinwell, 1866. Public domain

Our data

250 addresses where one or more people died

489 deaths

8 water pumps

Robin Wilson traced the deaths and pumps from Snow’s map, and lined them up with a modern map: johnsnow.rtwilson.com

Getting set up

Together 10 min

  1. Open the notebook from the course home page: Open the notebook in Colab
  2. File → Save a copy in Drive
  3. Run the first two cells (Shift + Enter)
%pip install --quiet "geopandas>=1.0" contextily folium mapclassify
import urllib.request
import zipfile

url = "https://johnsnow.rtwilson.com/data/SnowGIS_SHP.zip"
urllib.request.urlretrieve(url, "SnowGIS_SHP.zip")
with zipfile.ZipFile("SnowGIS_SHP.zip") as zip_file:
    zip_file.extractall()

01 Location data

How is location data stored, and what do the numbers mean?

What makes data geospatial?

Where A location: a point, a line or an area, given as coordinates

What The values we know about that place: the number of deaths at an address

Health examples Patients’ postcodes, GP surgeries, hospital catchments, air pollution

What it adds Location links datasets that share nothing else, and shows patterns a table can hide

Why location matters

“Everything is related to everything else, but near things are more related than distant things.”

Waldo Tobler’s “first law of geography”, 1970

  • Things close together tend to be alike: neighbouring streets share the same air, water and services
  • So a cluster that stands out from its surroundings is worth explaining
  • In 1854, a cluster of deaths around one pump pointed to the water

Two ways to store the world

Left: a map with a square polygon, a line and three points. Right: the same area as a grid of cells, shaded from pale to dark red
Vector Raster
Stores Shapes, each with a row of values A grid of cells, each with a value
Best for Things with edges: buildings, roads, addresses Things that vary smoothly: air pollution, temperature
Files Shapefile, GeoPackage, GeoJSON GeoTIFF
Python geopandas rasterio, xarray

Vector data: points, lines and polygons

Points An address, a pump, a hospital

Lines A road, a river, a bus route

Polygons A building, a postcode area, a catchment

A table of values + A geometry column = A GeoDataFrame

Reading the data

Together live code

import geopandas as gpd
import pandas as pd

deaths = gpd.read_file("SnowGIS_SHP/Cholera_Deaths.shp")
pumps = gpd.read_file("SnowGIS_SHP/Pumps.shp")
deaths.head()

GeoDataFrame A pandas DataFrame with a geometry column

Shapefile Several files that travel together: .shp, .dbf, .shx, .prj

Coordinate reference systems

Left: a globe with lines of latitude and longitude, and the Broad Street pump at 51.5133 north, 0.1367 west. Right: a flat grid in metres, with the same pump at 529,397 metres east and 181,025 metres north

A coordinate is just two numbers. The CRS says what they are measured from, and in what units

Geographic or projected?

Geographic CRS Latitude and longitude, in degrees, on the curved Earth. GPS and web maps use WGS 84 (EPSG:4326)

Projected CRS The Earth flattened onto a grid, in metres. The British National Grid (EPSG:27700) is made for Great Britain

✘ Flattening the Earth always distorts something: area, shape, distance or direction. No map keeps them all

✔ Measure distances and areas in a projected CRS made for your area

set_crs() or to_crs()?

# Label the data with its CRS: the numbers do not change
deaths = deaths.set_crs(27700, allow_override=True)
pumps = pumps.set_crs(27700, allow_override=True)

# Convert to latitude and longitude: the numbers change
deaths_latlon = deaths.to_crs(4326)

✔ set_crs() labels: use it when the CRS is missing or wrong

✔ to_crs() converts: use it to change CRS

✘ Measuring distances in latitude and longitude: the answer is in degrees

Where is pump 0?

Your turn 5 min

  1. Convert pumps to latitude and longitude
  2. Find the latitude and longitude of pump 0 (the first row)
  3. Paste them into Google Maps or OpenStreetMap as latitude, longitude. Which street is it on?

Hint: .geometry.y and .geometry.x. Exercise 1 in the notes.

Pump 0 is the Broad Street pump

Answer 3 min

pumps_latlon = pumps.to_crs(4326)
pumps_latlon.geometry.y.iloc[0], pumps_latlon.geometry.x.iloc[0]

About 51.5133, -0.1367: Broadwick Street, called Broad Street in 1854

Learn more about location data

Break

10 minutes

02 Making maps

How do we turn a table of points into a map that people can read?

What makes a good map?

The data The layer you want people to look at, drawn so it stands out

Context A background map, so readers know where they are

A key A legend or caption that says what the symbols mean

Credit Where the data and the background map came from

Showing values on a map

Good for In geopandas On Snow’s map
Size Amounts, such as a count markersize= The height of each stack of bars
Colour Amounts, or categories column=, cmap= Not used
Shape Different kinds of thing marker= Bars for deaths, dots for pumps

Snow showed the number of deaths at each address by the height of the stack: we will use the size of each dot

Layers

Together live code

ax = deaths.plot(
    color="black", markersize=deaths["Count"] * 10, alpha=0.7, figsize=(8, 8)
)
pumps.plot(ax=ax, color="blue", marker="^", markersize=80)
ax.set_axis_off()

Deaths + Pumps + Street map

A background map

import contextily as cx

ax = deaths.plot(
    color="black", markersize=deaths["Count"] * 10, alpha=0.7, figsize=(8, 8)
)
pumps.plot(ax=ax, color="blue", marker="^", markersize=80)
cx.add_basemap(ax, crs=deaths.crs, source=cx.providers.Esri.WorldStreetMap)
ax.set_axis_off()
  • crs=deaths.crs fits the map tiles to our data
  • Keep the attribution in the corner

An interactive map

deaths.explore(
    column="Count",
    cmap="Reds",
    marker_kwds={"radius": 4},
    tiles="Esri.WorldStreetMap",
)

.plot() Static: reports, papers, slides

.explore() Interactive: exploring data, web pages

An interactive map

Your turn 7 min

  1. Save the map of the deaths as m, with name="Deaths"
  2. Add the pumps: pumps.explore(m=m, color="blue", name="Pumps")
  3. Add a layer control: folium.LayerControl().add_to(m), after import folium
  4. Hover to find the address with the most deaths. Is it near a pump?

Exercise 2 in the notes.

The worst-hit address

Answer 3 min

m = deaths.explore(
    column="Count",
    cmap="Reds",
    marker_kwds={"radius": 4},
    tiles="Esri.WorldStreetMap",
    name="Deaths",
)
pumps.explore(m=m, color="blue", marker_kwds={"radius": 8}, name="Pumps")
folium.LayerControl().add_to(m)
m

worst = deaths.loc[deaths["Count"].idxmax()]
worst["geometry"].distance(pumps.geometry.iloc[0])

15 deaths, about 17 metres from the Broad Street pump

Learn more about maps

03 The nearest pump

Which pump was closest to each death?

Spatial relationships

Left: points coloured by which of three areas they fall in. Right: points joined by lines to the nearest of three pumps, and coloured to match

Two shapes can intersect, one can contain the other, or they can be a distance apart. These relationships let us join tables by location

Joining tables

Join by a column pd.merge(): rows with the same value in a shared column, such as a patient ID

Join by location sjoin(): rows whose shapes intersect, or where one contains the other

Join to the nearest sjoin_nearest(): each row to the closest row of the other table

A spatial join links datasets that share nothing but their location

Joining by location

Together live code

nearest = deaths.sjoin_nearest(pumps, distance_col="distance")
nearest.head()
  • index_right: the pump’s row (added by every spatial join)
  • pump_id: the pump’s number
  • distance: in metres, as the data is in the British National Grid

Deaths per pump

deaths_per_pump = nearest.groupby("pump_id")["Count"].sum()
deaths_per_pump.sort_values(ascending=False)
Pump 0 1 4 5 7 2 3 6
Deaths 340 65 40 27 12 5 0 0

70% of the 489 deaths were nearest the Broad Street pump

Deaths within 100 metres

Your turn 7 min

  1. broad_street = pumps.geometry.iloc[0]
  2. Use deaths.distance(broad_street) to find the addresses within 100 metres
  3. How many deaths were at those addresses? What percentage of all deaths?

Extra: broad_street.buffer(100) makes a 100 metre circle. Map it. Exercise 3 in the notes.

196 deaths within 100 metres

Answer 3 min

broad_street = pumps.geometry.iloc[0]
within_100m = deaths[deaths.distance(broad_street) <= 100]
deaths_near = within_100m["Count"].sum()
deaths_near, 100 * deaths_near / deaths["Count"].sum()

196 deaths, 40% of the total, within 100 metres of the pump

Learn more about spatial joins

04 Pump catchments

Which area did each pump serve?

Voronoi polygons

Five pumps, each inside its own coloured area. Every point in an area is closer to that area's pump than to any other

  • Each polygon is the area closest to one point
  • The edges are where you are the same distance from two points
  • Named after Georgy Voronoy (1908). Also called Thiessen polygons, after a meteorologist who used them for rainfall in 1911
  • Used today for catchments, such as the nearest GP surgery or hospital

Snow drew one too

For the parish’s inquiry, Snow redrew his map with a dotted line around the area closer to the Broad Street pump than to any other

  • He measured the distance along the streets, not in a straight line
  • It may be the earliest use of this kind of diagram

Voronoi polygons in geopandas

Together live code

from shapely.geometry import box

all_points = pd.concat([deaths.geometry, pumps.geometry])
xmin, ymin, xmax, ymax = all_points.total_bounds
study_area = box(xmin - 50, ymin - 50, xmax + 50, ymax + 50)

cells = pumps.voronoi_polygons(extend_to=study_area)
catchments = gpd.GeoDataFrame(geometry=cells)
catchments = catchments.sjoin(pumps, predicate="contains").clip(study_area)
  • The box gives the outer polygons an edge
  • The polygons are not in the order of the pumps, so a spatial join labels them

Deaths in each catchment

deaths_in_catchment = deaths.sjoin(catchments[["pump_id", "geometry"]])
deaths_in_catchment.groupby("pump_id")["Count"].sum()

The same totals as the nearest pump. Why?

Choropleth maps

What it is A map of areas, each shaded by a value

Counts mislead Areas with more people have more deaths, whatever the cause

Rates are fairer Deaths per 1,000 people compares areas with different populations

Our data We have no population figures, so we can only map counts

A map of catchments

Your turn 7 min

totals = deaths_in_catchment.groupby("pump_id")["Count"].sum()
catchments["deaths"] = catchments["pump_id"].map(totals).fillna(0)
  1. Plot catchments with column="deaths", cmap="Reds" and legend=True
  2. Add the pumps and a background map
  3. Which catchments had no deaths?

Exercise 4 in the notes.

The catchment map

Answer 3 min

ax = catchments.plot(
    column="deaths",
    cmap="Reds",
    legend=True,
    edgecolor="black",
    figsize=(8, 8),
)
pumps.plot(ax=ax, color="blue", marker="^", markersize=80)
cx.add_basemap(ax, crs=deaths.crs, source=cx.providers.Esri.WorldStreetMap)
ax.set_axis_off()

Pumps 3 and 6 had no deaths in their catchments

05 What the map cannot tell us

Should we believe it?

The evidence beyond the map

Straight lines For some homes the Rupert Street pump was closer, but dead ends made Broad Street quicker to reach

The brewery No deaths in the blocks east of the pump. The brewery had its own well, and its workers drank beer

The Hampstead widow Susannah Eley had Broad Street water delivered to Hampstead. She and her niece caught cholera

The first case A curate, Henry Whitehead, traced it to a baby at 40 Broad Street, whose washing water went into a cesspit by the pump

The limits of the data

  • Where people died, not where they drank: home addresses only
  • Who is missing: people who died somewhere else, like Susannah Eley
  • Traced by hand: the positions are approximate
  • Timing: the outbreak was already slowing when the handle was removed
  • Correlation, not cause: a cluster near a pump does not prove the pump caused it

The boundaries change the picture

The same set of points counted in four large squares and in nine smaller squares. With four squares, one corner looks worst; with nine, the centre does

The modifiable areal unit problem: the same data, counted in different areas, can show a different pattern

Question the map

Your turn 5 min

Pick one question, and answer in the chat:

  1. With only the catchment map and no interviews, what could you wrongly conclude?
  2. What extra data would make the analysis stronger?
  3. Think of location data from your own work. What would a map of it leave out?

Exercise 5 in the notes.

Summary

What you can now do

  • ✔ Load location data, and explain vector and raster data
  • ✔ Check and change a CRS, and measure in metres
  • ✔ Make static and interactive maps
  • ✔ Join tables by location
  • ✔ Draw catchments, and summarise data within them
  • ✔ Question what a map shows

Where next?

Image credits

  • John Snow’s map: public domain. Colour scan: Wellcome Collection
  • A London slum, 1860s: Wikimedia Commons, public domain
  • Cholera “Tramples the victors & the vanquished both”: Robert Seymour, 1831. National Library of Medicine, public domain
  • Death’s Dispensary: George J. Pinwell, Fun, 1866, public domain
  • Diagrams: Jean Golding Institute, CC BY 4.0

Thank you

Questions?