I used Claude Sonnet 5.5 to help generate these slides.
Roadmap for This Chapter
Understanding Spatial Data
Vocabulary: features, geometries, sf objects
Reading spatial files (shapefiles & co.)
Coordinate Reference Systems (CRS)
Projections: which one, and why it matters
Geometry operations (a short tour)
Making Maps
Basic maps with geom_sf()
Joining your data to geometries
Choropleth maps
Points, proportional symbols, heatmaps
Flow maps
Raster data
Exporting maps
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
Lovelace, Nowosad, and Muenchow (2025), Geocomputation with R: free online, the reference for everything spatial in R.
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:
the data carry geometries (points, lines, polygons), not just numbers,
positions are expressed in a Coordinate Reference System (CRS), and flattening a sphere onto a screen requires choices (projection),
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.
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:
How many features and how many attributes does it have? Which geometry type is it made of?
What does st_bbox(nc) return?
Use class(nc) and class(nc$geometry). What do you get?
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)).
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 automaticallydept <-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 URLzipf <-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 foldershp <-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").
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?
Read the shapefile with st_read(), then with read_sf(). What are the differences in the console and in the class of the result?
Write nc to a GeoPackage in data/nc.gpkg with st_write(), then read it back.
Write nc to a shapefile in data/nc_copy.shp. Which files appear in data/?
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 (892000, 6247000) as places on Earth. It combines:
A datum: a mathematical model of the Earth (ellipsoid) and how it is anchored to the real planet (WGS 84, ETRS89, RGF93, NAD27…).
A coordinate system: angles (latitude/longitude) or distances (metres, from an origin).
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 Africacells <-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 ellipsoidp_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 latitudeswidth_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.
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 planelabs(title ="North Carolina in a local projected CRS")
Task 3: Playing With CRS
What is the CRS of nc? Is it geographic or projected? Which units does it use?
Reproject nc to WGS 84 (4326) and to Web Mercator (3857). Print the bounding box of each version. What changes?
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?
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.
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 CRSmap_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.
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.
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
Read the CRS of the data first, never assume.
Store data in a sensible CRS, display with coord_sf(crs = ).
Choropleths: prefer equal-area projections.
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):
Draw the world in Web Mercator and in Equal Earth. Which continents appear bigger in Mercator?
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?
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.
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):
# 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
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:
Add the area of each county in km² as a column area_km2. Which county is the largest?
Compute the density BIR74 / area_km2. Which county has the highest density?
Compute the centroids with st_centroid() and with st_point_on_surface(). Plot the polygons with both sets of points in different colours.
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?
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.
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 CRSdatum =NULL, # NULL: no graticule; default is WGS 84 lon/latxlim =c(xmin, xmax), # zoom (in units of the display CRS!)ylim =c(ymin, ymax),expand =FALSE, # no padding around the datadefault_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-leftwidth_hint = .3# proportion of the plot area ) +annotation_north_arrow(location ="tl", # top-leftstyle =north_arrow_minimal() # north arrow style ) +theme_void()
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:
Different types: "01" (character) vs. 1 (numeric): left_join() raises an error, or fails silently when coerced.
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()).
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).
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 1974nc <- 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
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.
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:
Compute nwbirth_share = NWBIR74 / BIR74 (share of non-white births in 1974).
Draw a choropleth of nwbirth_share with a continuous sequential viridis scale.
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?
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.
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:
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).
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).
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:
Draw a proportional symbol map of n_sim. Add the city names for the 4 largest.
Draw the kernel density map again, but with bins = 4, then bins = 15. What changes?
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?
Redo the grid map with squares (square = TRUE). Which version do you find easier to read?
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:
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.
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.
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:
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
Add two rows of your own to the od table (using cities already in cities), and rebuild flow_lines.
Map the colour of the lines to the origin instead of using a fixed colour. Is the figure easier or harder to read?
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.
Display the map in Lambert-93, then in Web Mercator. Do the flows look different?
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.
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.
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.
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.abbcrs(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().
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]:
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.
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.
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.
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.
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.
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:
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())?
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.
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?
Compute the annual temperature range (max() − min() across layers) and map it. Where is it largest? How would you explain it?
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?
Extract the January and July temperatures at five cities of your choice (build the table with st_as_sf()).
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?
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().
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.
Get data for an indicator measured at the département level.
Download a shapefile with the boundaries of the départements and read it with {sf}.
Check, reproject and join the two sources.
Draw: a basic map, a choropleth, a comparison of classification methods, a proportional symbol map.
Polish and export your best map.
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
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).
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.
data/: your indicator dataset(s), as you downloaded them.
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
Ministries / agencies (Santé publique France, DREES…)
doctors per inhabitant, vaccination coverage, mortality
Requirements:
Download the file (script it with download.file() if the URL is stable, otherwise document the source and save the file in data/).
Import it with {readr} or {readxl}.
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?
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.
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
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.
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().
Run the “first checks” of the chapter: names(), nrow(), st_geometry_type(), st_crs(), st_bbox(), quick plot(st_geometry(...)).
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?
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
Build a clean join key in each table: character, two characters (str_pad() if necessary), and identical coding of 2A/2B.
Join the table to the boundaries with left_join() (boundaries on the left), and make sure the result is still an sf object.
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.
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?
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.
Basic map: borders of the départements only, light fill, thin borders.
Choropleth, continuous: your rate with an appropriate sequential scale (viridis or ColorBrewer). Give the legend a proper title.
Choropleth, classified: the same indicator with (a) equal intervals, (b) quantiles, displayed side by side with {patchwork}. Comment: how does the message change?
Diverging map (if relevant): map the gap to the national value (or to zero), with scale_fill_gradient2() and a meaningful midpoint.
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.
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
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.
Check the colours with colorblindr::cvd_grid() (see chapter 3). Is the map readable in greyscale?
Export it with ggsave(), as a PNG (dpi = 300) and a PDF, with dimensions suited for a slide. Compare file sizes.
Save the joined sf object as a GeoPackage in data/.
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.
Š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.