Course homepage

Data Visualization with R

Chapter 6 – Maps with {sf}

Ewen Gallic

October 21, 2026

Disclaimers

  1. I used Claude Sonnet 5.5 to help generate these slides.

Roadmap for This Chapter

Understanding Spatial Data

  1. Vocabulary: features, geometries, sf objects
  2. Reading spatial files (shapefiles & co.)
  3. Coordinate Reference Systems (CRS)
  4. Projections: which one, and why it matters
  5. Geometry operations (a short tour)

Making Maps

  1. Basic maps with geom_sf()
  2. Joining your data to geometries
  3. Choropleth maps
  4. Points, proportional symbols, heatmaps
  5. Flow maps
  6. Raster data
  7. Exporting maps
  8. Final exercise

Packages Used in This Chapter

install.packages(c(
  "sf",              # simple features: the core of this chapter
  "rnaturalearth",   # world boundaries (Natural Earth)
  "rnaturalearthdata",
  "ggspatial",       # scale bars, north arrows
  "terra",           # raster data (grids, NetCDF, GeoTIFF)
  "tidyterra",       # rasters in ggplot2: geom_spatraster()
  "patchwork"        # composition of plots
))

System Libraries Come With {sf}

{sf} is a thin R layer on top of several C/C++ libraries (GDAL, GEOS, PROJ, s2). On Windows and macOS, the binary packages from CRAN already bundle them, so a plain install.packages("sf") is enough.

flowchart LR
    S["<b>{sf}</b><br/>R interface"]
    G["<b>GDAL</b><br/>read / write file formats"]
    E["<b>GEOS</b><br/>planar geometry operations"]
    P["<b>PROJ</b><br/>CRS and transformations"]
    S2["<b>s2</b><br/>spherical geometry (lon/lat)"]

    S --> G
    S --> E
    S --> P
    S --> S2

    style S fill:#ffe5cc,stroke:#cc6600
    style G fill:#e6f0ff,stroke:#3366cc
    style E fill:#e6f0ff,stroke:#3366cc
    style P fill:#e6f0ff,stroke:#3366cc
    style S2 fill:#e6f0ff,stroke:#3366cc

Key References

Why Maps?

Maps Are Just Plots, With a Twist

  • A map is a plot where position on the page encodes a location on Earth.

  • Everything you learned in chapter 3 still applies: aesthetics, scales, colour choices, facets, themes.

  • What is new:

    1. the data carry geometries (points, lines, polygons), not just numbers,
    2. positions are expressed in a Coordinate Reference System (CRS), and flattening a sphere onto a screen requires choices (projection),
    3. a few typical map types deserve their own recipes: choropleths, proportional symbols, heatmaps, flows, …

Vector vs. Raster Data

Spatial data come in two families: vector (points, lines, polygons: what {sf} handles) and raster (grids of cells: weather and climate fields, satellite images, elevation, handled by {terra}). Most of this chapter is about vector data; a dedicated section near the end introduces raster data with a NOAA weather dataset.

A Map Can Mislead, Too

Remember the “When Visualization Goes Wrong” examples from the introduction. Maps offer their own traps:

  • a projection that inflates some regions and shrinks others,
  • a choropleth of raw counts that simply reproduces where people live,
  • classes (breaks) chosen so that the story you want appears,
  • large, sparsely populated areas that dominate the visual weight.

The Goal in this chapter

Learn the vocabulary well enough to choose consciously a CRS, a map type and a classification, rather than accepting defaults.

Spatial Data Vocabulary

Simple Features

{sf} stands for Simple Features, an open standard (OGC / ISO 19125) used by virtually all GIS software (PostGIS, QGIS, GeoPandas…). The vocabulary:

Term Meaning
Feature One spatial object: a city, a département, a river…
Geometry The shape of a feature: POINT, LINESTRING, POLYGON or their MULTI* versions
Attributes Ordinary variables describing the feature (name, population…)
CRS The system giving meaning to the coordinates
Bounding box The smallest rectangle containing all geometries

The Main Geometry Types

Type Example
POINT a city, a school, a station
LINESTRING a road, a river, a flow
POLYGON a département, a lake
MULTIPOINT / MULTILINESTRING / MULTIPOLYGON several parts treated as one feature

A MULTIPOLYGON Is Still One Feature

France is a single feature, yet its geometry is made of many polygons: mainland, Corsica, and each overseas territory.

pt <- st_point(c(1, 1))
ln <- st_linestring(rbind(c(0, 0), c(2, 1.5), c(3, 0)))
pg <- st_polygon(list(rbind(
  c(0, 2), c(1.5, 2), c(1.5, 3.5), c(0, 3.5), c(0, 2)
)))

shapes <- st_sf(
  type = c("POINT", "LINESTRING", "POLYGON"),
  geometry = st_sfc(pt, ln, pg)
)

ggplot(data = shapes) +
  geom_sf(
    mapping = aes(colour = type, fill = type), 
    size = 4, linewidth = 1.5, alpha = 0.8
  )

What Does an sf Object Look Like?

An sf object is a data frame with one special column: the geometry column (usually named geometry).

nc <- read_sf(system.file("shape/nc.shp", package = "sf"))
nc
Simple feature collection with 100 features and 14 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
Geodetic CRS:  NAD27
# A tibble: 100 × 15
    AREA PERIMETER CNTY_ CNTY_ID NAME  FIPS  FIPSNO CRESS_ID BIR74 SID74 NWBIR74
   <dbl>     <dbl> <dbl>   <dbl> <chr> <chr>  <dbl>    <int> <dbl> <dbl>   <dbl>
 1 0.114      1.44  1825    1825 Ashe  37009  37009        5  1091     1      10
 2 0.061      1.23  1827    1827 Alle… 37005  37005        3   487     0      10
 3 0.143      1.63  1828    1828 Surry 37171  37171       86  3188     5     208
 4 0.07       2.97  1831    1831 Curr… 37053  37053       27   508     1     123
 5 0.153      2.21  1832    1832 Nort… 37131  37131       66  1421     9    1066
 6 0.097      1.67  1833    1833 Hert… 37091  37091       46  1452     7     954
 7 0.062      1.55  1834    1834 Camd… 37029  37029       15   286     0     115
 8 0.091      1.28  1835    1835 Gates 37073  37073       37   420     0     254
 9 0.118      1.42  1836    1836 Warr… 37185  37185       93   968     4     748
10 0.124      1.43  1837    1837 Stok… 37169  37169       85  1612     1     160
# ℹ 90 more rows
# ℹ 4 more variables: BIR79 <dbl>, SID79 <dbl>, NWBIR79 <dbl>,
#   geometry <MULTIPOLYGON [°]>
  • The header summarises the geometry type, the bounding box and the CRS.
  • nc is included in {sf}: 100 North Carolina counties, with births and sudden infant deaths (SIDS) in 1974 and 1979.
  • Since it is a data frame, every {dplyr} verb works.

{dplyr} Works, and the Geometry Is “Sticky”

nc |>
  filter(BIR74 > 10000) |>
  select(NAME, BIR74) |>
  arrange(desc(BIR74))
Simple feature collection with 6 features and 2 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -81.06555 ymin: 34.45701 xmax: -77.12939 ymax: 36.25709
Geodetic CRS:  NAD27
# A tibble: 6 × 3
  NAME        BIR74                                                     geometry
  <chr>       <dbl>                                           <MULTIPOLYGON [°]>
1 Mecklenburg 21588 (((-81.0493 35.15153, -81.02396 35.14903, -81.00728 35.1632…
2 Cumberland  20366 (((-78.49929 34.85511, -78.51744 34.84353, -78.83166 34.844…
3 Guilford    16184 (((-79.53782 35.89097, -80.0426 35.91681, -80.0381 36.00618…
4 Wake        14484 (((-78.92107 35.57886, -78.99881 35.60132, -78.93889 35.761…
5 Forsyth     11858 (((-80.0381 36.00618, -80.12115 36.02155, -80.20988 36.0214…
6 Onslow      11158 (((-77.53864 34.45701, -77.57633 34.46935, -77.68983 34.720…

Sticky Geometry

select() never drops the geometry column: it comes along even though you did not ask for it. To get a plain tibble back, use st_drop_geometry():

nc |> st_drop_geometry() |> select(NAME, BIR74)

Likewise, group_by() + summarise() merges the geometries of each group (a spatial union). This is helpful to aggregate counties into regions!

Task 1: Exploring an sf Object

Using the nc object:

  1. How many features and how many attributes does it have? Which geometry type is it made of?
  2. What does st_bbox(nc) return?
  3. Use class(nc) and class(nc$geometry). What do you get?
  4. Create nc_small, containing the counties whose AREA is larger than 0.2, keeping only NAME and AREA. Plot it with plot(st_geometry(nc_small)).
  5. Create a tibble nc_tab without the geometry column. What class does it have now?

Reading Spatial Files

Common Spatial File Formats

Format Extension Comment
Shapefile .shp (+ .shx, .dbf, .prj…) Esri format from the 1990s, still shared a lot in open-data portals
GeoJSON .geojson Text, one file, standard for the web
GeoPackage .gpkg Modern, single-file, open
KML .kml Google Earth
CSV with lon/lat .csv Not a spatial format, but often how points are shared
  • st_read() and read_sf() read all of them (GDAL detects the format).
  • The difference: read_sf() returns a tibble and is silent, while st_read() returns a plain data frame and prints a summary.

The Shapefile: A “File” Made of Several Files

A shapefile is a set of files sharing the same name, which must stay together in the same folder:

File Content
.shp The geometries
.shx An index for the geometries
.dbf The attribute table
.prj The CRS (sometimes missing…)
.cpg The text encoding (optional)

Known Limitations of Shapefiles

  • Column names are truncated to 10 characters.
  • Each file is limited to about 2 GB.
  • A single geometry type per file.
  • Missing .prj means no CRS: you will have to find it out yourself.

When you save your own data, prefer GeoPackage (.gpkg).

Reading a Shapefile

library(sf)

# Point to the .shp file: the companion files are found automatically
dept <- read_sf("data/GEO_Contours_Departements/Departements.shp")

Typical workflow when the file comes as a .zip archive:

url  <- "https://example.org/some_boundaries.zip"   # replace by a real URL
zipf <- here("data", "boundaries.zip")

if (!file.exists(zipf)) {
  download.file(url, destfile = zipf, mode = "wb")   # "wb": binary mode (for Windows users)
}
unzip(zipf, exdir = here("data", "boundaries"))

# Find the .shp file inside the unzipped folder
shp <- list.files(here("data", "boundaries"), pattern = "\\.shp$",
                  recursive = TRUE, full.names = TRUE)
shp

Reading Directly From a Zip File

GDAL can read inside an archive: read_sf("/vsizip/data/boundaries.zip"). If accents look broken, try read_sf(shp, options = "ENCODING=UTF-8").

First Checks After Reading a File

Whenever you load a spatial file, run through this checklist before plotting anything:

names(dept)                  # which attributes? which column is the unique ID?
nrow(dept)                   # does the number of features match what you expect?
st_geometry_type(dept) |> unique()   # POLYGON? MULTIPOLYGON?
st_crs(dept)                 # which CRS?  (NA = no CRS defined)
st_bbox(dept)                # do the coordinates make sense for this CRS?
plot(st_geometry(dept))      # quick base-R look

plot() on an sf Object

Base plot() draws one small map per attribute (up to 9). Wrapping with st_geometry() draws only the shapes. This step constitues a fast sanity check, not a final figure.

Task 2: Reading a Shapefile

{sf} ships a shapefile you can read from disk: system.file("shape/nc.shp", package = "sf").

  1. Print the path returned by the call of system.file() above. List the files in that folder with list.files(). Which files share the name nc?
  2. Read the shapefile with st_read(), then with read_sf(). What are the differences in the console and in the class of the result?
  3. Write nc to a GeoPackage in data/nc.gpkg with st_write(), then read it back.
  4. Write nc to a shapefile in data/nc_copy.shp. Which files appear in data/?
  5. Compare the column names of the original and of the copy. Does anything change? (Think about the 10-character limit.)

Coordinate Reference Systems

What Is a CRS?

A Coordinate Reference System tells you how to interpret numbers like (5.37, 43.30) or (892 000, 6 247 000) as places on Earth. It combines:

  1. A datum: a mathematical model of the Earth (ellipsoid) and how it is anchored to the real planet (WGS 84, ETRS89, RGF93, NAD27…).
  2. A coordinate system: angles (latitude/longitude) or distances (metres, from an origin).
  3. Optionally, a projection: the mathematical recipe flattening the curved surface onto a plane.

Two Families of CRS

  • Geographic CRS: coordinates are angles on the ellipsoid, in degrees (longitude, latitude). No projection involved.
  • Projected CRS: coordinates are planar, in metres (or feet). Always based on a geographic CRS plus a projection.

Geographic vs. Projected: Units Matter

Geographic: WGS 84 (EPSG:4326)

st_crs(4326)$input
[1] "EPSG:4326"
st_crs(4326)$units_gdal
[1] "degree"

A degree of longitude is not a fixed distance: about 111 km at the equator, about 78 km at 45°N, zero at the poles.

Projected: Lambert-93 (EPSG:2154)

st_crs(2154)$input
[1] "EPSG:2154"
st_crs(2154)$units_gdal
[1] "metre"

A metre is a metre everywhere: distances and areas can be measured, within the limits of the projection.

EPSG Codes

Most CRS have an EPSG code, a short identifier from a public registry (see epsg.io). Giving {sf} the code is enough: st_crs(2154).

A Degree Is Not a Distance

Every cell below spans 10° × 10°: on a lon/lat plane they all look like identical squares.

# 10° x 10° cells covering Europe and North Africa
cells <- st_bbox(c(xmin = -20, ymin = 0, xmax = 40, ymax = 80), crs = st_crs(4326)) |>
  st_make_grid(cellsize = 10) |>
  st_as_sf() |>
  mutate(area_km2 = as.numeric(st_area(x)) / 1e6)   # geodesic area on the ellipsoid

p_grid <- ggplot(cells) +
  geom_sf(aes(fill = area_km2), colour = "white") +
  scale_fill_viridis_c(name = "Area (km²)", labels = scales::label_comma()) +
  labs(title = "Same size in degrees...") +
  theme_void()

# Width of 1° of longitude, at different latitudes
width_km <- tibble(lat = seq(0, 80, by = 10)) |>
  mutate(km = map_dbl(lat, \(l) {
    pts <- st_sfc(st_point(c(0, l)), st_point(c(1, l)), crs = 4326)
    as.numeric(st_distance(pts)[1, 2]) / 1000
  }))

p_width <- ggplot(width_km, aes(x = lat, y = km)) +
  geom_line() +
  geom_point() +
  labs(title = "...very different on the ground",
       x = "Latitude (°N)", y = "Width of 1° of longitude (km)")

# See next slide

A Degree Is Not a Distance

p_grid + p_width
  • A cell at 70–80°N covers about a quarter of the area of a cell at the equator (at 0°N).
  • Computing areas or distances in raw degrees would be meaningless: use a projected CRS, or let {sf} work on the sphere (s2).

Common CRS to Recognise

EPSG Name Type Typical use
4326 WGS 84 Geographic GPS, web data, GeoJSON, “lon/lat”
3857 Web Mercator Projected Web map tiles (Google Maps, OpenStreetMap)
4258 ETRS89 Geographic European official datum
3035 ETRS89 / LAEA Europe Projected Pan-European statistics (equal-area)
3034 ETRS89 / LCC Europe Projected Pan-European conformal maps
2154 RGF93 v1 / Lambert-93 Projected Official CRS of metropolitan France
4267 NAD27 Geographic Old North American datum (used by nc)
8857 WGS 84 / Equal Earth Projected World maps preserving areas

Reading a CRS in {sf}

st_crs(nc)$input   # label of the CRS
[1] "NAD27"
st_crs(nc)$epsg    # EPSG code, when it exists
[1] 4267
  • NA means no CRS: the numbers are just numbers, nothing is known about the locations.
  • The full description is stored as WKT (Well-Known Text); st_crs(nc) prints it. You rarely need to read it.
  • Anything accepted by PROJ works too: an EPSG code (4326), "EPSG:4326", or a PROJ string ("+proj=robin", see proj.org).

st_transform() vs. st_set_crs()

Two functions with similar names, and a very different meaning:

st_transform(): reproject

Converts the coordinates from the current CRS to another one. The shapes stay at the same place on Earth.

nc_4326 <- st_transform(nc, crs = 4326)
st_crs(nc_4326)$epsg
[1] 4326

st_crs<- / st_set_crs(): relabel

Declares which CRS the existing numbers already are in. Coordinates are untouched.

# Only when the CRS is MISSING (NA),
# and you know what it should be:
dept <- st_set_crs(dept, 2154)

Do not Make This Classic Mistake

Using st_set_crs() to “reproject” does not move anything: it just attaches a wrong label to the numbers and your map ends up in the Atlantic Ocean.

Rule:

  • CRS is NA: st_set_crs(),
  • CRS exists and differs from what you want: st_transform().

Data CRS vs. Display CRS

  • Each layer has its own CRS (the CRS of the data).
  • ggplot2 uses one CRS to draw the map (the display CRS): by default, the CRS of the first geom_sf() layer. Other layers are reprojected on the fly.
  • coord_sf(crs = ...) lets you choose the display CRS without touching your data.
ggplot(nc) +
  geom_sf() +
  coord_sf(crs = 32119) +    # NAD83 / North Carolina state plane
  labs(title = "North Carolina in a local projected CRS")

Task 3: Playing With CRS

  1. What is the CRS of nc? Is it geographic or projected? Which units does it use?
  2. Reproject nc to WGS 84 (4326) and to Web Mercator (3857). Print the bounding box of each version. What changes?
  3. Plot nc in its original CRS and in Web Mercator with coord_sf(crs = 3857), side by side with patchwork. Do you see a difference?
  4. On purpose, do wrong <- st_set_crs(nc_4326, 2154) (you will get a warning). Plot it. Where is the “map” now? Explain what happened.
  5. Which of st_transform() and st_set_crs() should be used when a shapefile arrives without a .prj file?

Projections

Flattening a Sphere: There Is No Free Lunch

A sphere cannot be flattened onto a plane without distortion (you cannot flatten an orange peel without tearing it). Every projection chooses what to preserve:

Property Preserved Sacrificed Used for
Conformal Angles, local shapes Areas Navigation, topographic maps
Equal-area Areas Shapes (angles) Statistical maps, choropleths
Equidistant Distances from one or two points Everything else Radio ranges, flight distances
Compromise A bit of everything Nothing exactly General-purpose world maps

Three Families (by Developable Surface)

Cylindrical (wrap a cylinder around the globe: Mercator), conic (a cone: Lambert-93, good for mid-latitude countries), azimuthal (a plane touching the globe: good for polar regions, or Europe in LAEA).

The World in Four Projections

world <- ne_countries(scale = "medium", returnclass = "sf") |>
  filter(continent != "Antarctica")

#' Map in a chosen display CRS
map_in <- function(crs, title) {
  ggplot(world) +
    geom_sf(fill = "grey80", colour = "white", linewidth = 0.1) +
    coord_sf(crs = crs) +
    labs(title = title) +
    theme_void()
}

(map_in(4326, "Plate carrée (lon/lat, EPSG:4326)") +
    map_in(3857, "Web Mercator (EPSG:3857)")) /
    (map_in("+proj=robin", "Robinson") +
       map_in("+proj=eqearth", "Equal Earth"))

# See the maps on next slide

The World in Four Projections

Mercator and the Size of Things

Mercator is conformal: it preserves angles, which is why it is perfect for navigation (and web tiles). But areas are inflated away from the equator.

areas <- world |>
  filter(name %in% c("Greenland", "Algeria", "Dem. Rep. Congo")) |>
  select(name)

areas |>
  mutate(
    true_km2     = as.numeric(st_area(geometry)) / 1e6,
    mercator_km2 = as.numeric(st_area(st_transform(geometry, 3857))) / 1e6,
    inflation    = mercator_km2 / true_km2
  ) |>
  st_drop_geometry()
             name true_km2 mercator_km2 inflation
1       Greenland  2154750     35395741 16.426844
2 Dem. Rep. Congo  2334630      2359632  1.010710
3         Algeria  2322749      3016589  1.298715
  • Greenland is roughly the size of Algeria or of the DR Congo. Africa as a whole is about 14 times larger than Greenland.
  • On a Mercator map, Greenland looks as big as Africa.
  • The st_area() on projected data measures the flattened polygons: using Web Mercator to compute areas gives nonsense.

Never Compute Areas or Distances in Web Mercator

Compute them either on lon/lat data ({sf} then uses spherical geometry via {s2}), or in an equal-area / local projected CRS.

Equal Earth: A Newly Endorsed Projection

  • Equal Earth was published in 2018 (Šavrič, Patterson, and Jenny (2018)). It is an equal-area projection with a Robinson-like shape: continents are shown with their true relative sizes.
  • On 4 September 2026, the UN General Assembly adopted a resolution (proposed by the African Group, with the “Correct the Map” initiative) encouraging member states to adopt and use Equal Earth and equal-area methods, notably in official documents and school textbooks. The vote reportedly gathered 164 states in favour, the United States voting against.
  • France co-sponsored the text and voted in favour; it has also announced it would stop using Mercator in its diplomatic communication.

Mercator Is Not “Wrong”

The resolution itself acknowledges that Mercator remains relevant for navigation and some regional or local uses. The point is matching the projection to the message: if the message is about the relative size of regions or the geography of a world statistic, use an equal-area projection.

coord_sf(crs = "+proj=eqearth")   # or crs = 8857

Projections for Europe and France

Pan-European: ETRS89

The European datum ETRS89 is tied to the stable part of the Eurasian plate. For mapping, the EU (INSPIRE directive, Eurostat) recommends:

  • ETRS89-LAEA (EPSG:3035): Lambert Azimuthal Equal-Area, for statistical analysis and display across Europe.
  • ETRS89-LCC (EPSG:3034): Lambert Conformal Conic, for conformal pan-European maps at small scales (1:500,000 or smaller).
  • ETRS89-TM zones: Transverse Mercator, for larger scales.

National: RGF93

France’s geodetic system is RGF93, a realisation of ETRS89. Its official projection for metropolitan France is:

  • Lambert-93 (EPSG:2154): a conic conformal projection, units in metres.
  • Overseas départements and regions have their own CRS (UTM-based): Lambert-93 is not suited for them.
  • RGF93 and WGS 84 differ by about a metre: irrelevant for data visualisation.

Europe in Different CRS

europe <- world |>
  filter(continent == "Europe") |>
  st_crop(xmin = -25, xmax = 45, ymin = 33, ymax = 72)

map_eu <- function(crs, title) {
  ggplot(europe) +
    geom_sf(fill = "grey85", colour = "white", linewidth = 0.1) +
    coord_sf(crs = crs) +
    labs(title = title) +
    theme_void()
}

map_eu(4326, "lon/lat (4326)") + map_eu(3857, "Web Mercator (3857)") + map_eu(3035, "ETRS89-LAEA (3035)")

Which CRS Should I Use?

You are mapping… Reasonable choice Why
The whole world Equal Earth (+proj=eqearth, 8857); Robinson for a classic look Areas preserved, no polar blow-up
Europe, statistics ETRS89-LAEA (3035) Equal-area, the EU standard
Metropolitan France Lambert-93 (2154) Official, low distortion
A US state / the US State plane / Albers (5070) National or local standard
A small area (city) Local UTM zone or national grid Minimal distortion
Data to overlay on a web basemap Web Mercator (3857) Tiles are in this CRS

Rules of Thumb

  1. Read the CRS of the data first, never assume.
  2. Store data in a sensible CRS, display with coord_sf(crs = ).
  3. Choropleths: prefer equal-area projections.
  4. Measure areas and distances in a CRS designed for it.

A Word on {s2} and Spherical Geometry

  • Since {sf} 1.0, operations on lon/lat data use the {s2} library: geometry on the sphere, not on a flat plane. That is why st_area() on lon/lat data returns correct areas.
  • Sometimes {s2} is stricter about invalid polygons and returns errors such as Loop 0 is not valid. Two classic ways out:
x <- st_make_valid(x)        # repair the geometries (try this first)
sf_use_s2(FALSE)             # fall back to planar GEOS (use sparingly)

Task 4: Choosing a Projection

Using world (from ne_countries(scale = "medium", returnclass = "sf"), without Antarctica):

  1. Draw the world in Web Mercator and in Equal Earth. Which continents appear bigger in Mercator?
  2. Compute the area of Russia, Brazil and Canada (in km²) with st_area() on the lon/lat data. Re-compute it after st_transform(3857). By how much does Mercator inflate each country?
  3. For each of the following maps, name the CRS you would pick and justify in one sentence: (a) GDP per capita of countries worldwide; (b) unemployment rates of NUTS-2 regions in the EU; (c) the distance between Paris and Marseille; (d) a thematic map of French départements.
  4. Draw Europe (continent == "Europe", cropped as in the slides) in ETRS89-LAEA (3035). Then in Lambert-93 (2154). Why does the second one look odd far from France?

Geometry Operations: A Short Tour

What Can You Do With Geometries?

{sf} function names all start with st_ (like “spatial type” in PostGIS):

Need Function Returns
Size st_area(), st_length() A number with units
Distances st_distance() A matrix of distances
Centre of a shape st_centroid(), st_point_on_surface() Points
Zone around a shape st_buffer() Polygons
Merge shapes st_union() One geometry
Overlap of two layers st_intersection() New geometries
Cut to a window st_crop() Cropped geometries
Simplify a boundary st_simplify() Lighter geometries
Test a relation st_intersects(), st_within()… Logical / index lists

Areas, With Units

nc |>
  mutate(
    area_km2 = as.numeric(units::set_units(st_area(geometry), km^2)),
    births_per_km2 = BIR74 / area_km2
  ) |>
  st_drop_geometry() |>
  select(NAME, area_km2, births_per_km2) |>
  arrange(desc(births_per_km2)) |>
  head(4)
# A tibble: 4 × 3
  NAME        area_km2 births_per_km2
  <chr>          <dbl>          <dbl>
1 Mecklenburg    1448.           14.9
2 New Hanover     431.           12.8
3 Cumberland     1739.           11.7
4 Forsyth        1084.           10.9
  • st_area() returns a units object (m² here), which protects you from mixing units. Use as.numeric() to get a plain number for ggplot2.
  • units::set_units() converts: km^2, ha…

st_centroid() vs. st_point_on_surface()

The centroid of a crescent-shaped or multi-part polygon can fall outside of it. st_point_on_surface() always returns a point lying inside the shape, which is safer for placing labels or symbols.

Spatial Joins and Predicates

A spatial join attaches attributes using location instead of a shared key: “in which county is each point?”

set.seed(42)
pts <- st_sample(nc, 300) |> st_as_sf() # 300 random points

# point-in-polygon
pts_in_county <- st_join(pts, nc["NAME"])

pts_in_county |>
  st_drop_geometry() |>
  count(NAME, sort = TRUE) |>
  head(5)
      NAME  n
1 Randolph 10
2 Carteret  8
3   Craven  7
4   Duplin  7
5  Jackson  7
  • st_join() uses st_intersects() by default; change it with the join argument (st_within, st_nearest_feature…).

Task 5: Geometry Operations

Using nc:

  1. Add the area of each county in km² as a column area_km2. Which county is the largest?
  2. Compute the density BIR74 / area_km2. Which county has the highest density?
  3. Compute the centroids with st_centroid() and with st_point_on_surface(). Plot the polygons with both sets of points in different colours.
  4. Using the pts_in_county object from the slide, compute the number of random points per county. Do the counts look proportional to county areas? Why should they be?
  5. Create a 20 km buffer around Wake County (NAME == "Wake") with st_buffer(). (Hint: you must first reproject to a CRS in metres, e.g. 32119.) Which counties intersect this buffer?

Basic Maps with {ggplot2}

geom_sf(): The Only Geometry You Need

geom_sf() draws whatever the geometry column contains (points, lines or polygons) and sets up coord_sf() for you.

ggplot(data = nc) +
  geom_sf()
  • No x and y mapping: the position comes from the geometry.
  • Aesthetics (fill, colour, linewidth, alpha…) work as usual: mapping vs. setting still applies.

Styling a Map

ggplot(data = nc) +
  geom_sf(
    fill = "grey95", colour = "grey40",
    linewidth = 0.2
  ) +
  theme_void() +
  labs(
    title = "North Carolina counties",
    caption = "Source: sf package (nc.shp)"
  )
  • colour = border, fill = interior (as in chapter 3).
  • theme_void() removes axes and grid: often the cleanest choice for a map.
  • Keep theme_minimal() if the graticule (coordinates) is useful to the reader.

Layers: Combining Several Spatial Datasets

Each geom_sf() layer can have its own data; all are reprojected to the display CRS.

nc_centroids <- st_centroid(nc)

ggplot() +
  geom_sf(data = nc, fill = "grey95", colour = "grey60", linewidth = 0.2) +
  geom_sf(data = nc_centroids, colour = "firebrick", size = 1) +
  theme_void()

The Graticule and coord_sf()

By default, geom_sf() draws a graticule (grid of meridians and parallels) in lon/lat, whatever the display CRS. Its behaviour is controlled in coord_sf():

coord_sf(
  crs      = 2154,          # display CRS
  datum    = NULL,          # NULL: no graticule; default is WGS 84 lon/lat
  xlim     = c(xmin, xmax), # zoom (in units of the display CRS!)
  ylim     = c(ymin, ymax),
  expand   = FALSE,         # no padding around the data
  default_crs = NULL        # CRS assumed for NON-sf layers (see later)
)

Zooming Uses the CRS Units

xlim/ylim are expressed in the display CRS units: degrees if you are in lon/lat, metres if you are in Lambert-93. If you want to give limits in lon/lat while displaying in another CRS, add default_crs = st_crs(4326).

Cartographic Elements: Scale Bar and North Arrow

{ggspatial} adds the classic elements of a map (note that scale bars only make sense in projections where scale is roughly constant on the map).

ggplot(data = nc) +
  geom_sf(fill = "grey95", colour = "grey40", linewidth = 0.2) +
  annotation_scale(
    location = "bl", # bottom-left
    width_hint = .3  # proportion of the plot area
    ) +
  annotation_north_arrow(
    location = "tl", # top-left
    style = north_arrow_minimal() # north arrow style
  ) +
  theme_void()

Labels on Maps

big_counties <- nc |> slice_max(BIR74, n = 6)

ggplot() +
  geom_sf(data = nc, fill = "grey95", colour = "grey70", linewidth = 0.2) +
  geom_sf(data = big_counties, fill = "steelblue", alpha = 0.6) +
  geom_sf_text(data = big_counties, aes(label = NAME), size = 3.5, fontface = "bold") +
  theme_void()
  • geom_sf_text() / geom_sf_label() place labels at (an interior point of) each geometry.

Task 6: Your First Maps

Using nc:

  1. Draw a map of the counties with a light grey fill and thin white borders, with theme_void().
  2. Map fill to AREA. Which scale did ggplot2 pick by default?
  3. Highlight in a different colour the 5 counties with the highest BIR74, and label them.
  4. Add a scale bar and a north arrow.
  5. Display the same map in coord_sf(crs = 32119) with datum = NULL. Compare with the default graticule version.

Joining Your Data to Geometries

The Typical Situation

Most of the time, geometries and the variable you want to map live in two different files:

  • a boundary file (shapefile, GeoPackage) with a unique identifier,
  • a table (CSV, Excel) with the same identifier and your statistics.

You already know the tool: left_join() from {dplyr} (chapter 2).

Put the sf Object on the Left

  • left_join(boundaries, table) returns an sf object.
  • left_join(table, boundaries) returns a plain tibble (the geometry column is no longer recognised as such): the map can no longer be drawn directly.

A Join, Step by Step

We split nc into a boundary file and a table to mimic the usual workflow:

boundaries <- nc |> select(FIPS)                                      # geometry + id
stats      <- nc |> st_drop_geometry() |> select(FIPS, SID74, BIR74)  # table + id

Assume these are the boundary file and the table you want to merge:

boundaries
Simple feature collection with 100 features and 1 field
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
Geodetic CRS:  NAD27
# A tibble: 100 × 2
   FIPS                                                                 geometry
   <chr>                                                      <MULTIPOLYGON [°]>
 1 37009 (((-81.47276 36.23436, -81.54084 36.27251, -81.56198 36.27359, -81.633…
 2 37005 (((-81.23989 36.36536, -81.24069 36.37942, -81.26284 36.40504, -81.266…
 3 37171 (((-80.45634 36.24256, -80.47639 36.25473, -80.53688 36.25674, -80.545…
 4 37053 (((-76.00897 36.3196, -76.01735 36.33773, -76.03288 36.33598, -76.0439…
 5 37131 (((-77.21767 36.24098, -77.23461 36.2146, -77.29861 36.21153, -77.2935…
 6 37091 (((-76.74506 36.23392, -76.98069 36.23024, -76.99475 36.23558, -77.130…
 7 37029 (((-76.00897 36.3196, -75.95718 36.19377, -75.98134 36.16973, -76.1831…
 8 37073 (((-76.56251 36.34057, -76.60424 36.31498, -76.64822 36.31532, -76.688…
 9 37185 (((-78.30876 36.26004, -78.28293 36.29188, -78.32125 36.54553, -78.051…
10 37169 (((-80.02567 36.25023, -80.45301 36.25709, -80.43531 36.55104, -80.048…
# ℹ 90 more rows
stats
# A tibble: 100 × 3
   FIPS  SID74 BIR74
   <chr> <dbl> <dbl>
 1 37009     1  1091
 2 37005     0   487
 3 37171     5  3188
 4 37053     1   508
 5 37131     9  1421
 6 37091     7  1452
 7 37029     0   286
 8 37073     0   420
 9 37185     4   968
10 37169     1  1612
# ℹ 90 more rows

A Join, Step by Step

nc_joined <- boundaries |>
  left_join(stats, by = "FIPS")

class(nc_joined)
[1] "sf"         "tbl_df"     "tbl"        "data.frame"

Always check that the join worked as expected:

# Geometries without a match in the table (should be 0 rows)
boundaries |> anti_join(stats, by = "FIPS") |> nrow()
[1] 0
# Rows of the table without geometry (should be 0 rows)
stats |> anti_join(st_drop_geometry(boundaries), by = "FIPS") |> nrow()
[1] 0
# No duplicated geometries after the join?
nrow(nc_joined) == nrow(boundaries)
[1] TRUE

Why Do Joins Fail?

The three usual suspects:

  1. Different types: "01" (character) vs. 1 (numeric): left_join() raises an error, or fails silently when coerced.
  2. Lost leading zeros: Excel and CSV imports turn "01" into 1. Fix: str_pad(code, width = 2, pad = "0"), or read the column as text with col_types = cols(code = col_character()).
  3. Different codes or spellings: names with accents, hyphens, different code vintages (communes merge!), special codes such as 2A / 2B (Corsica).

Join on Codes, Not on Names

Official codes (INSEE, NUTS, ISO) are far more robust than names.

Pro tip: always count the unmatched rows with anti_join() before mapping. A missing département shows up as a silent grey hole in your map.

Choropleth Maps

What Is a Choropleth?

A choropleth map fills each area (country, région, département, commune…) with a colour that encodes a variable.

  • Probably the most common type of statistical map.
  • The variable must be normalised: rates, shares, densities, per-capita values: not raw counts.
  • Colour scale: sequential for magnitudes, diverging when there is a meaningful midpoint (see chapter 3).
  • Technically, nothing new: geom_sf(aes(fill = variable)).

Counts vs. Rates

Same data, two very different maps: the number of SIDS deaths mostly shows where babies are born, the rate shows risk.

# SID74: Sudden infant death syndrome in 1974
# BIR74: Total births in 1974
nc <- nc |> mutate(sids_rate = 1000 * SID74 / BIR74)

p_count <- ggplot(nc) +
  geom_sf(
    mapping = aes(fill = SID74), colour = "white", linewidth = 0.2
  ) +
  scale_fill_viridis_c(option = "mako", direction = -1) +
  labs(title = "Counts", fill = "Deaths") +
  theme_void()

p_rate <- ggplot(nc) +
  geom_sf(
    mapping = aes(fill = sids_rate), colour = "white", linewidth = 0.2
  ) +
  scale_fill_viridis_c(option = "mako", direction = -1) +
  labs(title = "Rate per 1,000 births", fill = "Rate") +
  theme_void()
p_count / p_rate

Classifying a Continuous Variable

A choropleth can use a continuous colour gradient, or classes (bins). Classes make maps easier to read (legend with discrete colours) but the choice of breaks changes the story.

Method Principle Strength Weakness
Equal interval Classes of the same width Easy to explain Empty classes if skewed data
Quantiles Same number of areas per class Always uses all colours Can split similar values, merge very different ones
Natural breaks (Jenks/Fisher) Minimise variance within classes Follows the data Hard to explain, not comparable between maps
Manual Thresholds you choose Meaningful cutoffs (e.g. a legal threshold) Subjective

Equal Intervals vs. Quantiles

#' Helper function
choro <- function(data, fill_var, title) {
  ggplot(data) +
    geom_sf(
      mapping = aes(fill = {{ fill_var }}), 
      colour = "white", linewidth = 0.2
    ) +
    scale_fill_viridis_d(
      option = "mako", direction = -1, drop = FALSE
    ) +
    labs(title = title, fill = NULL) +
    theme_void() +
    theme(legend.position = "bottom")
}

Classes of the same width vs. quantiled-based classes:

nc <- nc |>
  mutate(
    rate_equal = cut_interval(sids_rate, n = 5), # equal widths
    rate_quantile = cut_number(sids_rate, n = 5) # equal counts
  )
choro(nc, rate_equal, "Equal intervals") / 
  choro(nc, rate_quantile, "Quantiles")

Reading the Difference

  • With equal intervals, a few high-rate counties are isolated in the top classes, and the bottom classes contain most of the map.
  • With quantiles, each class has the same number of counties, so the map looks “balanced”… even if the variable is not.
  • Neither is “the truth”. If you present a classified map, say how the classes were built, and test whether your message survives a change of method.

More Classification Methods

The package {classInt} offers classIntervals(x, n = 5, style = "jenks") (also "fisher", "sd", "pretty"…). Its $brks can be passed to cut().

Diverging Scales: Mapping Deviations

If the question is above or below a reference (the state average, zero, the national rate), a diverging palette with a meaningful midpoint is the right choice.

state_rate <- 1000 * sum(nc$SID74) / sum(nc$BIR74)

nc |>
  mutate(gap = sids_rate - state_rate) |>
  ggplot() +
  geom_sf(
    mapping = aes(fill = gap), 
    colour = "white", linewidth = 0.2
  ) +
  scale_fill_gradient2(
    low = "dodgerblue", mid = "grey95", 
    high = "firebrick", midpoint = 0
  ) +
  labs(fill = "Gap to state rate\n(per 1,000 births)") +
  theme_void()

The Pitfalls of Choropleths

Area bias

Large, sparsely populated areas catch the eye even if few people live there. A département of 100,000 inhabitants takes the same space as one with 2 million.

Modifiable Areal Unit Problem (MAUP)

The pattern you see depends on the way space is cut: communes, départements, régions can tell different stories about the same phenomenon.

Alternatives

  • Proportional symbols: circles sized by a count (next section).
  • Cartograms: distort areas to be proportional to a variable (e.g. the {cartogram} package).
  • Tile grid maps: one equal square per area.
  • Heatmaps/grids: aggregate on a regular grid, which removes the dependence on administrative boundaries.

Mapping an Unreliable Estimate

Rates computed on small populations are noisy. Consider mapping the population size alongside, or smoothing.

Task 7: Your First Choropleths

Using nc:

  1. Compute nwbirth_share = NWBIR74 / BIR74 (share of non-white births in 1974).
  2. Draw a choropleth of nwbirth_share with a continuous sequential viridis scale.
  3. Draw the same map with 4 classes built with cut_number(), and another one with 4 classes built with cut_interval(). Which one do you find more informative? Why?
  4. Compute the 1979 SIDS rate, sids_rate_79, and the change between 1974 and 1979. Which type of colour scale should you use for the change? Draw the map.
  5. Using patchwork, draw the 1974 and 1979 rates side by side with the same colour scale limits. Why does this matter?

Points, Proportional Symbols and Heatmaps

A Dataset for the Next Examples

For the next sections, we need a map of mainland France and a few cities. We crop the Natural Earth “France” polygon (which also contains overseas territories) to the mainland and Corsica:

france <- ne_countries(scale = "medium", country = "France", returnclass = "sf") |>
  st_crop(xmin = -6, xmax = 10, ymin = 41, ymax = 52) |>
  st_transform(2154)                       # Lambert-93

cities <- tribble(
  ~city,        ~lon,    ~lat,   ~n_sim,
  "Paris",       2.3522, 48.8566, 600,
  "Lyon",        4.8357, 45.7640, 250,
  "Marseille",   5.3698, 43.2965, 250,
  "Toulouse",    1.4442, 43.6047, 180,
  "Bordeaux",   -0.5792, 44.8378, 160,
  "Lille",       3.0573, 50.6292, 160,
  "Nantes",     -1.5536, 47.2184, 140,
  "Strasbourg",  7.7521, 48.5734, 120,
  "Nice",        7.2620, 43.7102, 120,
  "Rennes",     -1.6778, 48.1173, 100
)

These cities as an sf object:

cities_sf <- st_as_sf(cities, coords = c("lon", "lat"), crs = 4326)

From a Table With lon/lat to Points

The classic conversion: st_as_sf() with coords (order: x = longitude first, then y = latitude) and the CRS of those coordinates (almost always 4326 for GPS-like coordinates).

ggplot() +
  geom_sf(
    data = france, fill = "grey95", 
    colour = "grey60", linewidth = 0.2
  ) +
  geom_sf(
    data = cities_sf, colour = "firebrick", size = 2
  ) +
  geom_sf_text(
    data = cities_sf, 
    mapping = aes(label = city), 
    nudge_y = 40000, size = 3.5
  ) +
  theme_void()

Latitude/Longitude Swapped?

If your points land in the ocean (or in another continent), you probably inverted lon and lat. You can have a quick check with the bounding box (st_bbox()).

Proportional Symbol Maps

When the variable is a count (a quantity, not a rate), size the points by value: the eye reads the area of the circle.

cities_sf |>
  ggplot() +
  geom_sf(
    data = france, fill = "grey95", 
    colour = "grey60", linewidth = 0.2
  ) +
  geom_sf(
    mapping = aes(size = n_sim), 
    colour = "firebrick", alpha = 0.6
  ) +
  scale_size_area(
    max_size = 14, name = "Simulated\nobservations"
  ) +
  theme_void()

  • The default scale_size() already does map to area but does not start at zero!
  • Use scale_size_area(), which maps value to area, with 0 mapped to 0.

Heatmaps: Density of Points

A heatmap (density map) shows where points are concentrated, independently of administrative boundaries. We simulate 2,080 point locations around the ten cities (think of addresses, accidents, transactions).

set.seed(2026)
sim_points <- cities |>
  slice(rep(seq_len(n()), times = n_sim)) |>
  mutate(
    lon = lon + rnorm(n(), sd = 0.25),
    lat = lat + rnorm(n(), sd = 0.20)
  )

points_sf <- st_as_sf(
  sim_points, coords = c("lon", "lat"), crs = 4326
) |>
  st_transform(2154)

ggplot() +
  geom_sf(data = france, fill = "grey98") +
  geom_sf(data = points_sf, size = .1)

2D Kernel Density With {ggplot2}

stat_density_2d_filled() estimates a 2D density from x and y columns, so we extract the projected coordinates first.

points_xy <- points_sf |>
  mutate(
    X = st_coordinates(geometry)[, 1], 
    Y = st_coordinates(geometry)[, 2]
  )
ggplot() +
  geom_sf(
    data = france, fill = "grey98", 
    colour = "grey60", linewidth = 0.2
  ) +
  stat_density_2d_filled(
    data = points_xy, 
    mapping = aes(x = X, y = Y), 
    alpha = 0.7, bins = 8
    ) +
  scale_fill_viridis_d(
    option = "rocket", direction = -1, 
    name = "Density"
    ) +
  theme_void()

Density on the Whole Country

stat_density_2d_filled() only evaluates the density on the range of the points: parts of France outside that box get no value. We can compute the density ourselves on a grid covering all of France.

bb <- st_bbox(france)

kde <- MASS::kde2d(
  points_xy$X, points_xy$Y, n = 300,
  lims = c(bb["xmin"], bb["xmax"], bb["ymin"], bb["ymax"])
)
dens <- expand_grid(Y = kde$y, X = kde$x) |>
  mutate(z = as.vector(kde$z))

outside <- st_as_sfc(bb) |> st_difference(st_union(france)) # bbox minus France

And then plot it.

ggplot() +
  geom_contour_filled(
    data = dens, aes(x = X, y = Y, z = z), 
    bins = 8, alpha = 0.7
  ) +
  geom_sf(data = outside, fill = "white", colour = NA) +
  geom_sf(
    data = france, fill = NA, colour = "grey60", 
    linewidth = 0.2
  ) +
  scale_fill_viridis_d(
    option = "rocket", direction = -1, 
    name = "Density"
  ) +
  theme_void()

  • MASS::kde2d() lets us set the evaluation window with lims: far from the points, the density is simply very small.

Non-sf Layers and default_crs

In the previous map, the X and Y columns are ordinary numbers: ggplot2 has to guess their CRS.

  • Rule: layers that are not sf objects are assumed to be in the display CRS (here Lambert-93, taken from the first geom_sf() layer) (which is correct, because we extracted projected coordinates).
  • If your x/y columns are lon/lat, tell coord_sf():
ggplot() +
  geom_sf(data = france) +
  stat_density_2d_filled(data = sim_points, aes(x = lon, y = lat)) +
  coord_sf(crs = 2154, default_crs = st_crs(4326))

Kernel Density in Lon/Lat Is Distorted

A kernel in degrees is wider in kilometres in the north-south direction than in the east-west direction. Prefer estimating densities in a projected CRS in metres, as done here.

Heatmaps: Counting Points in a Grid

An alternative is to aggregate points in a regular grid (squares or hexagons) and map the counts: no smoothing parameter, and the result is a regular choropleth.

hex <- st_make_grid( # 40 km hexagons
  france, cellsize = 40000, square = FALSE
)
hex <- st_sf(hex_id = seq_along(hex), geometry = hex)

hex_counts <- st_join(points_sf, hex) |>
  st_drop_geometry() |>
  count(hex_id)

The plot:

hex |>
  inner_join(hex_counts, by = "hex_id") |>
  ggplot() +
  geom_sf(
    data = france, fill = "grey98", 
    colour = "grey60", linewidth = 0.2
    ) +
  geom_sf(aes(fill = n), colour = NA) +
  scale_fill_viridis_c(
    option = "rocket", direction = -1, trans = "sqrt"
    ) +
  theme_void()

Density Estimate or Grid?

Kernel density Grid (hexagons / squares)
Output Smooth surface Discrete cells
Main parameter Bandwidth (smoothness) Cell size
Strength Pleasant, reveals clusters Honest: counts are visible and exact
Weakness Suggests continuity that may not exist; bandwidth changes the story Arbitrary cell size and positions

Hexagons

Hexagons may be preferred over squares: all neighbours are at the same distance, which reduces visual artefacts.

Task 8: Points and Heatmaps

Using france, cities and points_sf from the previous slides:

  1. Draw a proportional symbol map of n_sim. Add the city names for the 4 largest.
  2. Draw the kernel density map again, but with bins = 4, then bins = 15. What changes?
  3. Change the grid map to hexagons of 20 km, then of 80 km. How does the pattern change? Which size do you find most appropriate?
  4. Redo the grid map with squares (square = TRUE). Which version do you find easier to read?
  5. Which of the three representations (proportional symbols, density, grid) would you use to show to a non-specialist audience where activity is concentrated? Justify.

Flow Maps

Mapping Flows: Origins and Destinations

A flow map shows movements between locations: commuting, migration, trade, passengers. The data come as an origin–destination (OD) table:

od <- tribble(
  ~origin,      ~dest,        ~flow,
  "Paris",      "Lyon",        120,
  "Paris",      "Marseille",    90,
  "Paris",      "Bordeaux",     75,
  "Paris",      "Lille",        65,
  "Paris",      "Strasbourg",   40,
  "Lyon",       "Marseille",    55,
  "Toulouse",   "Bordeaux",     45,
  "Nantes",     "Rennes",       35,
  "Marseille",  "Nice",         50,
  "Lyon",       "Strasbourg",   25
)

Note

These flows are fictitious, for illustration only.

From an OD Table to Lines

Add the coordinates of origin and destination, then, build one LINESTRING per row.

coords <- cities |> select(city, lon, lat)
flow_lines <- od |>
  left_join(coords, by = c("origin" = "city")) |> 
  rename(lon_o = lon, lat_o = lat) |>
  left_join(coords, by = c("dest" = "city")) |> 
  rename(lon_d = lon, lat_d = lat) |>
  mutate(
    geometry = st_sfc(
      pmap(
        list(lon_o, lat_o, lon_d, lat_d),
        \(x1, y1, x2, y2) st_linestring(
          rbind(c(x1, y1), c(x2, y2))
        )
      ),
      crs = 4326
    )
  ) |>
  st_as_sf()
flow_lines |> select(origin, dest, flow)
Simple feature collection with 10 features and 3 fields
Geometry type: LINESTRING
Dimension:     XY
Bounding box:  xmin: -1.6778 ymin: 43.2965 xmax: 7.7521 ymax: 50.6292
Geodetic CRS:  WGS 84
# A tibble: 10 × 4
   origin    dest        flow                           geometry
   <chr>     <chr>      <dbl>                   <LINESTRING [°]>
 1 Paris     Lyon         120    (2.3522 48.8566, 4.8357 45.764)
 2 Paris     Marseille     90   (2.3522 48.8566, 5.3698 43.2965)
 3 Paris     Bordeaux      75  (2.3522 48.8566, -0.5792 44.8378)
 4 Paris     Lille         65   (2.3522 48.8566, 3.0573 50.6292)
 5 Paris     Strasbourg    40   (2.3522 48.8566, 7.7521 48.5734)
 6 Lyon      Marseille     55    (4.8357 45.764, 5.3698 43.2965)
 7 Toulouse  Bordeaux      45  (1.4442 43.6047, -0.5792 44.8378)
 8 Nantes    Rennes        35 (-1.5536 47.2184, -1.6778 48.1173)
 9 Marseille Nice          50    (5.3698 43.2965, 7.262 43.7102)
10 Lyon      Strasbourg    25    (4.8357 45.764, 7.7521 48.5734)

How pmap() Works

The pmap() function

pmap() iterates over several arguments simultaneously: it takes a list of vectors, and calls the function once per position, using the i-th element of each vector.

a <- 1:3
b <- 4:6
d <- 7:9
pmap(list(a, b, d), \(x1, x2, x3) c(x1, x2, x3))
[[1]]
[1] 1 4 7

[[2]]
[1] 2 5 8

[[3]]
[1] 3 6 9
  • Call 1 gets (1, 4, 7), call 2 gets (2, 5, 8), call 3 gets (3, 6, 9): the output is a list with one element per call.
  • In our flow table, list(lon_o, lat_o, lon_d, lat_d) has one call per row: each call receives the four coordinates of one OD pair and returns one LINESTRING.

Drawing the Flows

ggplot() +
  geom_sf(
    data = france, fill = "grey95", 
    colour = "grey60", linewidth = 0.2
  ) +
  geom_sf(
    data = flow_lines, 
    mapping = aes(linewidth = flow), 
    colour = "firebrick", alpha = 0.6
  ) +
  geom_sf(data = cities_sf, size = 1.5) +
  geom_sf_text(
    data = cities_sf, 
    mapping = aes(label = city), 
    nudge_y = 40000, size = 3.5
  ) +
  scale_linewidth(range = c(0.4, 3), name = "Flow") +
  theme_void()

Making Flow Maps Readable

  • Line width encodes the intensity. Draw large flows first (or last), and use transparency.
  • Direction is the hard part. Options: net flows only (A → B minus B → A), colour by origin, small arrowheads.
  • Straight lines are not what they seem: a segment in lon/lat becomes a curve once projected. For long distances, densify the line with st_segmentize() before projecting:
flow_lines <- st_segmentize(flow_lines, dfMaxLength = units::set_units(20, km))

Curved Arrows and coord_sf()

geom_curve() is not available with coord_sf() (non-linear coordinates). Curves require a workaround (projecting first and using a Cartesian coordinate system), or dedicated packages for flow maps. In this course, straight line widths are enough.

Too Many Flows?

A flow map with hundreds of lines is a hairball. Filter on the largest flows, aggregate to coarser units (régions rather than communes), or switch to a matrix/chord representation.

Task 9: A Flow Map

  1. Add two rows of your own to the od table (using cities already in cities), and rebuild flow_lines.
  2. Map the colour of the lines to the origin instead of using a fixed colour. Is the figure easier or harder to read?
  3. Compute, for each city, the total outflow (origin) and the total inflow (dest) with group_by() and summarise(). Show them as proportional symbols (two colours) on top of the flow lines.
  4. Display the map in Lambert-93, then in Web Mercator. Do the flows look different?
  5. Which problem would arise if the table contained 5,000 flows?

Raster Data

Vector vs. Raster, Revisited

Vector ({sf})

  • Discrete objects: a département, a road, a city.
  • Geometries are points, lines, polygons, with an attribute table.
  • Boundaries are exact (up to digitisation).
  • Typical: administrative boundaries, networks, locations.

Raster ({terra})

  • A continuous field sampled on a regular grid of cells: temperature, rainfall, elevation, night lights, land cover.
  • Each cell holds a value; the grid is defined by an extent, a resolution and a CRS.
  • Can have several layers (months, years, spectral bands).
  • Typical: weather and climate models, satellite images, …

Common Raster Formats

GeoTIFF (.tif, images and elevation), NetCDF (.nc, the standard for weather and climate data: several variables, several dates, self-described), GRIB (.grib2, operational weather forecasts). {terra} reads all of them with rast().

Raster at a Glance

We build a tiny raster by hand: 4 rows and 6 columns covering a 6° × 4° box.

library(terra)
library(tidyterra)

r_toy <- rast(
  nrows = 4, ncols = 6,
  xmin = 0, xmax = 6, ymin = 0, ymax = 4,
  crs = "EPSG:4326"
)
set.seed(1)
values(r_toy) <- round(runif(ncell(r_toy), 0, 30))
names(r_toy) <- "value"

r_toy
class       : SpatRaster
size        : 4, 6, 1  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 6, 0, 4  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326)
source(s)   : memory
name        : value
min value   :     2
max value   :    30
ggplot() +
  geom_spatraster(data = r_toy) +
  scale_fill_viridis_c() +
  coord_sf(expand = FALSE)

  • nrow(), ncol(), ncell(), res(), ext(), crs(), nlyr() describe the grid. Cells are stored row by row, from the top-left corner.
  • as.data.frame(r_toy, xy = TRUE) returns one row per cell: the “tidy” version of a raster. If the grid is too large, this call will take a lot of time.

A Raster Can Have Several Layers

Each layer is one variable (or one date) on the same grid. We add a second layer to our toy raster.

r_rain <- rast(r_toy)            # same grid, no values
set.seed(2)
values(r_rain) <- round(runif(ncell(r_rain), 0, 30))

r_stack <- c(r_toy, r_rain)      # stack the layers
names(r_stack) <- c("temp", "rain")

nlyr(r_stack)
[1] 2
r_stack
class       : SpatRaster
size        : 4, 6, 2  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 6, 0, 4  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326)
source(s)   : memory
names       : temp, rain
min values  :    2,    2
max values  :   30,   29
ggplot() +
  geom_spatraster(data = r_stack) +
  facet_wrap(~ lyr) +
  scale_fill_viridis_c() +
  coord_sf(expand = FALSE)

  • Pick a layer with r_stack[["rain"]] or r_stack$rain. Layers must share the same extent, resolution and CRS to be combined with c().
  • Raster algebra works layer by layer or across layers: r_stack$temp - r_stack$rain.
  • as.data.frame(r_stack, xy = TRUE) gives one row per cell and one column per layer.

A Real Dataset: NOAA Reanalysis

We use a small weather dataset from the NOAA Physical Sciences Laboratory (PSL):

  • NCEP/NCAR Reanalysis 1: weather observations assimilated into a global model, giving gridded fields of temperature, pressure, wind…
  • File: monthly long-term mean of near-surface air temperature (air.sig995.mon.ltm.nc: temperature at the sigma 0.995 level, i.e. a few tens of metres above the ground).
  • Format: NetCDF, on a regular 2.5° × 2.5° grid (about 280 km at the equator), with 12 layers: one per calendar month.
url <- paste0(
  "https://psl.noaa.gov/thredds/fileServer/Datasets/",
  "ncep.reanalysis.derived/surface/air.sig995.mon.ltm.nc"
)
nc_file <- here("data", "air.sig995.mon.ltm.nc")

if (!file.exists(nc_file)) {
  dir.create(dirname(nc_file), showWarnings = FALSE)
  download.file(url, destfile = nc_file, mode = "wb")   # "wb" again!
}
file.size(nc_file) / 1e6   # size in MB
[1] 0.657356

A Real Dataset: NOAA Reanalysis

Not Every NetCDF File Is a Raster

The NOAA Physical Sciences Laboratory also provides the same variable on a Gaussian grid (the surface_gauss/ folder, e.g. air.2m.mon.ltm.nc) whose latitudes are not regularly spaced:

  • {terra} cannot read it as a raster (lat is not regularly spaced): a raster needs cells of constant size;
  • such grids call for {stars}, or for resampling onto a regular grid.

Check the grid of a file before choosing the tool!

Reading a NetCDF File With rast()

A NetCDF file can contain several variables (“subdatasets”). This one contains the temperature (air) and a technical variable (valid_yr_count):

describe(nc_file, sds = TRUE)
  id
1  1
2  2
3  3
                                                                                                                                    name
1 NETCDF:"/Users/ewengallic/Dropbox/Universite_Aix_Marseille/Enseignements/Data-viz/cours/data/air.sig995.mon.ltm.nc":climatology_bounds
2                NETCDF:"/Users/ewengallic/Dropbox/Universite_Aix_Marseille/Enseignements/Data-viz/cours/data/air.sig995.mon.ltm.nc":air
3     NETCDF:"/Users/ewengallic/Dropbox/Universite_Aix_Marseille/Enseignements/Data-viz/cours/data/air.sig995.mon.ltm.nc":valid_yr_count
                 var                                              desc nrow
1 climatology_bounds [12x2] climatology_bounds (64-bit floating-point)   12
2                air           [12x73x144] air (32-bit floating-point)   73
3     valid_yr_count       [12x73x144] valid_yr_count (16-bit integer)   73
  ncol nlyr
1    2    1
2  144   12
3  144   12

Reading a NetCDF File With rast()

r <- rast(nc_file, subds = "air")
r
class       : SpatRaster
size        : 73, 144, 12  (nrow, ncol, nlyr)
dimensions  : lon, lat, time (144, 73, 12}
resolution  : 2.5, 2.5  (x, y)
extent      : -1.25, 358.75, -91.25, 91.25  (xmin, xmax, ymin, ymax)
coord. ref. : 
source      : air.sig995.mon.ltm.nc
varname     : air (Long Term Mean Monthly Mean Air Temperature at sigma level 0.995)
names       : air_1, air_2, air_3, air_4, air_5, air_6, ...
unit        : degC
time        : 0000-12-30 00:00:00 to 0001-11-29 00:00:00 (12 steps)
  • dimensions: rows, columns, layers (here 12 months). resolution: cell size, in degrees. extent, coord. ref.: as for any spatial object.
  • A NetCDF file is self-describing: variables, dimensions, units and dates are stored in the file itself (units(r), time(r)).
  • Without argument subds, rast() would load all variables as layers.
  • Rename the layers to something readable, and declare the CRS (see the warning below):
names(r) <- month.abb
crs(r) <- "EPSG:4326"

This File Has No CRS

Weather models output values on a lon/lat grid but often do not store a CRS in the file: crs(r) is then empty, and project() fails with input raster CRS not set (and overlaying with sf layers would be meaningless). It is the same rule as for vector data: CRS missing → declare it (crs(r) <- ..., the {terra} counterpart of st_set_crs()), after checking in the documentation that coordinates are indeed lon/lat. Reprojecting is project(), the counterpart of st_transform().

Two Things to Check Before Mapping

1. The extent

ext(r)   # -1.25, 358.75, -91.25, 91.25
SpatExtent : -1.25, 358.75, -91.25, 91.25 (xmin, xmax, ymin, ymax)

Two oddities:

  • Longitudes run from 0° to 360° (common in climate data): Europe is on the left of the map, the Americas on the right.
  • Latitudes go beyond ±90°: the file stores values at grid points (poles included), but {terra} treats each value as the centre of a cell, so the border cells stick out by half a cell (1.25°).

Since the 144 × 73 values are meant to cover the whole globe, we declare it, then rotate() to [-180, 180]:

ext(r) <- ext(0, 360, -90, 90)
r <- rotate(r)
ext(r)   # -180, 180, -90, 90
SpatExtent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)

This is an approximation: positions move by up to about 1.25°, invisible on a 2.5° world map. For work needing exact locations, resample onto a proper global grid instead.

2. Units

Raster files hold numbers, not meanings: always check the units (metadata, documentation, or just look at the values!).

global(r, "mean", na.rm = TRUE) |> head(3)
        mean
Jan 3.730807
Feb 3.036740
Mar 2.695552

The file declares no units (units(r) is empty), so we judge from the values. Monthly means around 3 can only be degrees Celsius: in Kelvin they would be around 250 to 300.

units(r) # empty: nothing declared
 [1] "" "" "" "" "" "" "" "" "" "" "" ""
global(r, "range", na.rm = TRUE) |> head(3) # plausible temperatures?
          min      max
Jan -37.52723 33.59648
Feb -42.55101 32.62389
Mar -54.29798 32.45131
units(r) <- "degC" # we set the label ourselves

If they had been in Kelvin, raster algebra would convert them: -273.15 subtracts the constant from every cell of every layer.

Raster Algebra and Layer Operations

Arithmetic and summary functions work cell by cell, on all layers at once:

jul    <- r[["Jul"]]      # pick one layer by name (here, July)
annual <- mean(r)         # mean over the 12 layers (per cell)
ampl   <- max(r) - min(r) # annual temperature range (per cell)

names(annual) <- "annual_mean"
names(ampl)   <- "amplitude"
Goal Function
One value per cell, from all layers mean(r), max(r), min(r), sum(r), app(r, fun)
One value per layer, from all cells global(r, "mean", na.rm = TRUE)
Select layers r[["Jul"]], r[[c("Jan", "Jul")]], subset(r, 1:3)
Arithmetic -273.15, r1 - r2 (logical raster)

Plotting a Raster With {ggplot2}

{tidyterra} provides geom_spatraster(), which plays nicely with geom_sf() and the rest of {ggplot2}: the cell values are mapped to fill.

ggplot() +
  geom_spatraster(data = jul) +
  geom_sf(
    data = world, fill = NA, 
    colour = "white", linewidth = 0.15
  ) +
  scale_fill_viridis_c(option = "inferno", name = "°C") +
  labs(
    title = "Mean July near-surface temperature (long-term mean)", 
    caption = "Source: NOAA PSL, NCEP/NCAR Reanalysis 1"
  ) +
  theme_void()

Several Layers: Facets

When the raster has several layers, geom_spatraster() creates a lyr variable that you can facet on.

ggplot() +
  geom_spatraster(
    data = r[[c("Jan", "Apr", "Jul", "Oct")]]
  ) +
  facet_wrap(~ lyr, ncol = 2) +
  scale_fill_viridis_c(
    option = "inferno", name = "°C"
  ) +
  theme_void()

Note

With faceting, the same colour scale is shared by all panels: compare them directly, as in chapter 3 (small multiples).

Colour Scales for Rasters

  • Temperature is a continuous variable: sequential palettes (viridis, inferno…) are the default choice.
  • If the message is above or below freezing, a diverging scale with a meaningful midpoint makes sense:
ggplot() +
  geom_spatraster(data = jul) +
  scale_fill_gradient2(
    low = "dodgerblue", mid = "grey95", 
    high = "firebrick",
    midpoint = 0, name = "°C"
  ) +
  theme_void()

  • Rainbow palettes (rainbow, jet) are common in meteorology but misleading (see the colour section of chapter 3): avoid them.

Rasters and Projections

A raster is a regular grid in its own CRS. Reprojecting it means computing new cell values on a new grid (unlike vector data where only vertex coordinates change): this requires interpolation.

jul_ee <- project(jul, "+proj=eqearth", method = "bilinear")

ggplot() +
  geom_spatraster(data = jul_ee) +
  geom_sf(
    data = world, fill = NA, 
    colour = "white", linewidth = 0.15
  ) +
  scale_fill_viridis_c(
    option = "inferno", na.value = "transparent", 
    name = "°C"
  ) +
  theme_void()

method When
"near" Categorical rasters (land cover classes): never invents new values
"bilinear", "cubic" Continuous rasters (temperature, elevation)

Cropping and Masking

  • crop() cuts the raster to a rectangular extent. mask() sets to NA the cells falling outside a polygon layer.
  • vect() converts an sf object into a SpatVector, the vector class of {terra}.
r_eu <- crop(r, ext(-15, 45, 33, 72)) |>
  mask(vect(europe))

ggplot() +
  geom_spatraster(data = r_eu[["Jan"]]) +
  geom_sf(
    data = europe, fill = NA, 
    colour = "white", linewidth = 0.2
  ) +
  scale_fill_viridis_c(
    option = "inferno", na.value = "transparent", 
    name = "°C"
  ) +
  labs(title = "January mean temperature, Europe") +
  theme_void()

Mind the Resolution

Cells are about 280 km wide at the equator: coastlines and countries are only roughly resolved. Don’t over-interpret a map at a finer scale than its grid (a département of France is smaller than a cell).

From Raster to Vector Data (1): Values at Points

terra::extract() reads the raster values at locations (points, lines or polygons): this is how rasters meet the rest of your data.

vals <- terra::extract(
  r[[c("Jan", "Jul")]], 
  vect(cities_sf), 
  method = "bilinear"
)

vals

cities |>
  select(city) |>
  bind_cols(select(vals, Jan, Jul)) |>
  mutate(range = Jul - Jan)
   ID       Jan      Jul
1   1 5.1556906 18.17294
2   2 2.1242283 19.04776
3   3 5.3147872 20.86829
4   4 5.5311668 20.07354
5   5 8.3767887 19.12699
6   6 5.3577026 17.31339
7   7 8.6882214 17.51573
8   8 0.8809806 17.95916
9   9 4.1511375 20.23762
10 10 8.0212258 16.85192
# A tibble: 10 × 4
   city         Jan   Jul range
   <chr>      <dbl> <dbl> <dbl>
 1 Paris      5.16   18.2 13.0 
 2 Lyon       2.12   19.0 16.9 
 3 Marseille  5.31   20.9 15.6 
 4 Toulouse   5.53   20.1 14.5 
 5 Bordeaux   8.38   19.1 10.8 
 6 Lille      5.36   17.3 12.0 
 7 Nantes     8.69   17.5  8.83
 8 Strasbourg 0.881  18.0 17.1 
 9 Nice       4.15   20.2 16.1 
10 Rennes     8.02   16.9  8.83
  • method = "bilinear" interpolates between the 4 nearest cell centres; the default takes the value of the cell containing the point.
  • Note that Marseille and Nice, about 160 km apart, are within a cell or two of each other: the dataset can hardly tell them apart. Reanalysis fields describe regional climate, not local weather.

From Raster to Vector Data (2): Zonal Statistics

Zonal statistics summarise the cells falling in each polygon: here, the annual mean temperature of each country.

zs <- terra::extract(
  annual, 
  vect(world), 
  fun = mean, na.rm = TRUE, exact = TRUE
)

world |>
  mutate(t_mean = zs$annual_mean) |>
  ggplot() +
  geom_sf(
    mapping = aes(fill = t_mean), 
    colour = "white", linewidth = 0.1
  ) +
  scale_fill_viridis_c(option = "inferno", name = "°C") +
  coord_sf(crs = "+proj=eqearth") +
  theme_void()

  • exact = TRUE weights the cells by the fraction of each cell covered by the polygon: important when polygons are small compared to the cells.
  • The result is a plain table aligned with the polygons: join it back, and you are in the choropleth world of the previous section.

Task 10: A NOAA Raster Map

Starting from the NOAA file air.sig995.mon.ltm.nc:

  1. List its variables with describe(..., sds = TRUE), then read the temperature with rast(..., subds = "air"). How many rows, columns and layers does it have? What is the resolution in degrees? How many cells in total (ncell())?
  2. Check its CRS (crs(r)) and declare it if it is missing. Rotate it to [-180, 180], trim its latitude range to [-90, 90] with crop(), check the units, and convert to °C.
  3. Map the mean temperature of January and of July side by side with a common scale. Which type of palette did you choose and why?
  4. Compute the annual temperature range (max() − min() across layers) and map it. Where is it largest? How would you explain it?
  5. Draw your July map in three versions: plain lon/lat, Robinson ("+proj=robin") and Equal Earth. Which one would you use in a report, and why?
  6. Extract the January and July temperatures at five cities of your choice (build the table with st_as_sf()).
  7. Compute the mean annual temperature of each country (zonal statistics), then the average by continent (use group_by()). Which continent is warmest? Is a simple average of countries the right way to answer this? Why not?
  8. Bonus: download another variable from the same NOAA PSL page (e.g. precipitation rate), and produce a map of the wettest month.

Exporting Maps

Saving Maps

  • Same function as in chapter 3: ggsave(), with explicit width, height, units and dpi.
  • Maps with many polygons (communes!) can produce heavy PDFs (every vertex is stored): consider PNG, or simplify the geometries with st_simplify().
ggsave(
  filename = "figs/map_rates.png",
  plot = p_rate,
  width = 7, height = 6, units = "in", dpi = 300
)

Saving spatial data:

st_write(nc, "data/nc_with_rates.gpkg")   # GeoPackage: recommended
write_sf(nc, "data/nc_with_rates.gpkg", delete_dsn = TRUE)   # overwrite quietly

st_simplify() Needs Care

Simplify in a projected CRS with a tolerance in metres (dTolerance = 1000), and set preserveTopology = TRUE (default) to avoid creating gaps between neighbouring polygons.

Final Exercise: Mapping the French Départements

Task 11: Overview

You will produce a small atlas of France at the département level: from open data to a polished figure.

  1. Get data for an indicator measured at the département level.
  2. Download a shapefile with the boundaries of the départements and read it with {sf}.
  3. Check, reproject and join the two sources.
  4. Draw: a basic map, a choropleth, a comparison of classification methods, a proportional symbol map.
  5. Polish and export your best map.
  6. Reflect on your choices (CRS, scale, classes).

Work in an R script saved in an RStudio project, and write your answers in a separate document (see next slide).

What to Hand In

Send one .zip archive named Lastname_Firstname_maps.zip, with this structure:

Lastname_Firstname_maps/
├── Lastname_Firstname_maps.Rproj   # the RStudio project
├── script.R                        # ONE script doing everything
├── answers.pdf                     # your answers to the questions
├── data/
│   └── (your indicator file(s), as downloaded)
└── figs/
    └── (the figures exported by your script)
├── project.Rproj                   # The RStudio project file
  1. script.R: a single script that performs all the tasks, from reading the data to exporting the maps. Comment it, with one section per part (A to E).
  2. answers.pdf: your answers to all the questions, written in a word processor (Word, LibreOffice, Google Docs…) and exported to PDF. Number your answers like the questions, and include your key maps.
  3. data/: your indicator dataset(s), as you downloaded them.
  4. Do NOT include the IGN files (the shapefile of the départements). I will use my own copy, in data/ign/: your script must read it from there.

What to Hand In

I Will Run Your Script: It Must Reproduce Your Results

Points are deducted if I cannot run your code and obtain the same results. Before sending, test it:

  • Make sure you start from an empty workspace: in RStudio, go to Tools → Global Options → General, untick “Restore .RData into workspace at startup”, and set “Save workspace to .RData on exit” to “Never”. Then restart R (Session → Restart R) and check that the Environment pane is empty.
  • Run the whole script from top to bottom. It must run without error and without any object created in the console or loaded from an old session.
  • Do not include any .RData, .Rhistory or .Rproj.user file in your archive.
  • Load every package with library() at the top of the script.
  • No absolute paths (C:/Users/..., ~/Desktop/...) and no setwd(): use paths relative to the project folder ("data/...", "figs/..."), and open the project via the .Rproj file.
  • Do not rely on the internet: all the data must be read from data/.
  • Create the figs/ folder from the script if needed (dir.create("figs", showWarnings = FALSE)), and save your figures with ggsave().
  • Use set.seed() if your code uses random numbers.
  • Test it one last time, with the IGN files in data/ign/, from a fresh session.
  • Last step: once the test passes, delete the IGN files (the whole data/ign/ folder) from your project folder, and only then create the .zip archive. Do not run the script again after deleting them.

Part A: Get Départemental Data

Pick one indicator available for every département (at least 96 of metropolitan France). Some sources and ideas:

Source Possible indicators
INSEE (statistics, “Chiffres détaillés” and “Bases de données”) population, population density, unemployment rate, poverty rate, median income, share of 65+, share of graduates
data.gouv.fr crime and delinquency statistics, hospital capacity, cycling infrastructure, electric-vehicle charging points
Ministries / agencies (Santé publique France, DREES…) doctors per inhabitant, vaccination coverage, mortality

Requirements:

  1. Download the file (script it with download.file() if the URL is stable, otherwise document the source and save the file in data/).
  2. Import it with {readr} or {readxl}.
  3. Identify the column holding the département code. Is it character or numeric? Does it keep the leading zero ("01")? How are Corsica ("2A", "2B") and the overseas départements ("971"…) coded?
  4. Make sure your indicator is a rate, a share or a density for the choropleth. If you only have counts, find a population table and compute a rate. Keep the raw count too: you will need it for the proportional symbol map.

Part B: Which IGN File?

The IGN ADMIN EXPRESS product (official administrative boundaries, free) offers more than 200 files. Use the filters of the download tool (France métropolitaine, SHP, Lambert-93), then read the file name: it is a code.

ADMIN-EXPRESS-COG-CARTO-PE_3-1__SHP_LAMB93_FXX_2024-04-15

Part Meaning What to choose
COG, COG-CARTO, COG-CARTO-PE Level of detail: COG = full precision (huge); CARTO = generalised, medium scale; CARTO-PE = more simplified, small scale (light) COG-CARTO-PE: simplified enough to be light and fast to draw, precise enough for a national map
3-1 Version of the product The most recent one
SHP / GPKG Format: shapefile or GeoPackage Either; GeoPackage is a single file
LAMB93 / WGS84G CRS: Lambert-93 (metres) or lon/lat WGS 84 LAMB93 for metropolitan France
FXX / FRA / GLP, MTQ… Territory: metropolitan France, all of France, or one overseas département FXX for the main maps
2024-04-15 Edition date The most recent one

Check Before You Download

IGN reorganises its catalogue regularly: the version and date above are an example, and not every combination exists. Read the file name before downloading, and say in your document which file you chose and why.

Part B: Get and Read the Boundaries

  1. On the cartes.gouv.fr download page, filter on France métropolitaine, format SHP and Lambert-93, then pick a COG-CARTO-PE file (most recent edition). Note the licence. The archive is about 15 MB. Create a folder data/ign/ in your project and save the archive inside it.
  2. The archive is a .7z: extract it in the same folder, data/ign/ (with 7-Zip / Keka, or archive::archive_extract() in R). It contains many layers: find the one for the départements with list.files("data/ign", recursive = TRUE, pattern = "DEPARTEMENT\\.shp$"), then read it with read_sf().
  3. Run the “first checks” of the chapter: names(), nrow(), st_geometry_type(), st_crs(), st_bbox(), quick plot(st_geometry(...)).
  4. Answer in your document: Which CRS is the file in? Is it geographic or projected? Does the number of features match what you expect (96 for metropolitan France, 101 with the overseas départements)? Which column holds the département code?
  5. If you kept the whole of France (FRA), keep the metropolitan départements for the main maps (remove "971", "972", "973", "974", "976"), and transform them to Lambert-93 (st_transform(2154)). Why is this the right CRS here?

Part C: Join and Validate

  1. Build a clean join key in each table: character, two characters (str_pad() if necessary), and identical coding of 2A/2B.
  2. Join the table to the boundaries with left_join() (boundaries on the left), and make sure the result is still an sf object.
  3. Validate the join: use anti_join() in both directions. How many départements are unmatched? Fix the keys until there is no unexpected mismatch, and document what you did.
  4. Compute the final variable(s) for the map (rate, share, density…) with mutate(). Look at their distribution first with a histogram: is it symmetric or skewed? Are there outliers? How will this affect your classification?
  5. Add the area of each département in km² (st_area()), and compute the population density if you have population.

Part D: Draw the Maps

Draw the following, in this order. Use theme_void() (or a theme of your choice), keep all maps in the same CRS.

  1. Basic map: borders of the départements only, light fill, thin borders.
  2. Choropleth, continuous: your rate with an appropriate sequential scale (viridis or ColorBrewer). Give the legend a proper title.
  3. Choropleth, classified: the same indicator with (a) equal intervals, (b) quantiles, displayed side by side with {patchwork}. Comment: how does the message change?
  4. Diverging map (if relevant): map the gap to the national value (or to zero), with scale_fill_gradient2() and a meaningful midpoint.
  5. Proportional symbols: map the count (number of unemployed, of inhabitants, of poor households…) as circles centred on st_point_on_surface() of each département, over a light-grey basemap.
  6. Combination: a choropleth of the rate with proportional symbols of the count on top. Is the figure still readable?

Part E: Polish, Check and Export

  1. Pick your best map and polish it: a title that states the message (“…” rather than “Map of …”), a subtitle, a legend title with units, a caption with the data sources (INSEE/IGN, year, licence), a scale bar if relevant.

  2. Check the colours with colorblindr::cvd_grid() (see chapter 3). Is the map readable in greyscale?

  3. Export it with ggsave(), as a PNG (dpi = 300) and a PDF, with dimensions suited for a slide. Compare file sizes.

  4. Save the joined sf object as a GeoPackage in data/.

  5. Reflect, in 4 to 6 sentences:

    • What does your map show? What does it hide?
    • Would you have drawn a different map had the unit been the commune or the région?
    • What would have happened with the default lon/lat display, or with Web Mercator?
    • Which choice of classification did you finally keep and why?

Part F: Going Further (Optional)

Pick one or more:

  • Overseas départements: map the 5 overseas départements in a separate panel, each in its own local CRS (see epsg.io), and assemble with {patchwork} as insets around the mainland map.
  • Two dates: if your indicator exists for two years, build two choropleths with a common scale, or a map of the change with a diverging scale. Facets work on sf objects: facet_wrap(~ year).
  • Heatmap: if your data are geolocated points (stations, accidents, real-estate transactions), draw a density map or a hexagonal grid over France.
  • Hexagonal tile map: build a grid map in which each département is one equal-sized hexagon, as an alternative to the area bias of the choropleth.

Summary of the Chapter

Concepts

  • A map is a plot whose positions come from geometries in a CRS.
  • Geographic CRS (degrees) vs. projected CRS (metres).
  • Projections preserve angles, areas, distances: not all at once. Choose according to the message.
  • Data CRS vs. display CRS (coord_sf(crs = )).

Recipes

  • read_sf(), st_crs(), st_transform(), st_set_crs().
  • geom_sf() + theme_void().
  • Joins: sf on the left, check with anti_join().
  • Choropleth: rates, not counts; classes matter.
  • Symbols, densities, grids and flows for what choropleths cannot show.
  • Rasters: rast(), rotate(), raster algebra, geom_spatraster(), project(), crop()/mask(), terra::extract() for points and zonal statistics.
Lovelace, Robin, Jakub Nowosad, and Jannes Muenchow. 2025. Geocomputation with r. Chapman; Hall/CRC.
Pebesma, Edzer, and Roger Bivand. 2023. Spatial Data Science: With Applications in r. Chapman; Hall/CRC. https://doi.org/10.1201/9780429459016.
Šavrič, Bojan, Tom Patterson, and Bernhard Jenny. 2018. “The Equal Earth Map Projection.” International Journal of Geographical Information Science 33 (3): 454–65. https://doi.org/10.1080/13658816.2018.1504949.