Skip to contents

The SVG of a flow map is a finished figure. Sometimes the figure should sit on a map instead: over streets and place names, with zoom and pan. milkflow does not draw web maps itself. It writes the figure as GeoJSON, and a web-map package draws that. This article does it with mapgl, the R interface to MapLibre GL JS, in about thirty lines.

It needs two packages besides milkflow, neither of which milkflow depends on:

Real places

A web map needs real coordinates, so the package’s invented towns will not do. The example is the public transport of the Recife metropolitan region, in Brazil: journeys between its 15 municipalities on a working day, aggregated from electronic ticketing, with the municipal positions in SIRGAS 2000 / UTM zone 25S (EPSG:31985). Each flow has as category the part of the region where the journey starts. The file is one of the examples of the milkflow site.

rmr <- jsonlite::fromJSON(
  "https://strategicprojects.github.io/milkflow/data/rmr_municipios_linhas.json"
)
head(rmr$nodes, 3)
#>        id      x       y                   label weight
#> 1 2600054 290513 9125881            Abreu e Lima  24173
#> 2 2601052 269076 9138445               Araçoiaba    475
#> 3 2602902 275386 9083254 Cabo de Santo Agostinho  37910
head(rmr$flows, 3)
#>    origin destination value category
#> 1 2600054     2600054  5716    Norte
#> 2 2600054     2603454   291    Norte
#> 3 2600054     2606804  1772    Norte

The figure as GeoJSON

geojson = TRUE asks for the drawn figure as GeoJSON, next to the SVG.

m <- flowmap(rmr$nodes, rmr$flows, crs = rmr$crs, units = rmr$units,
             geojson = TRUE, style = list(lang = "en"))
m
Flow map 37% of the volume in 15 segments · 63% internal to the places Oeste Jaboatão dos Guararapes → Recife: 0 Recife → Jaboatão dos Guararapes: 1,129 Total: 1,129 · 1% of the segment Recife Jaboatão dos Guararapes → Recife: 0 Recife → Jaboatão dos Guararapes: 52,279 Total: 52,279 · 47% of the segment Sul Jaboatão dos Guararapes → Recife: 56,527 Recife → Jaboatão dos Guararapes: 0 Total: 56,527 · 50% of the segment Norte Jaboatão dos Guararapes → Recife: 0 Recife → Jaboatão dos Guararapes: 2,022 Total: 2,022 · 2% of the segment Norte Olinda → Recife: 35,315 Recife → Olinda: 0 Total: 35,315 · 51% of the segment Sul Olinda → Recife: 0 Recife → Olinda: 1,190 Total: 1,190 · 2% of the segment Oeste Olinda → Recife: 0 Recife → Olinda: 347 Total: 347 · 1% of the segment Recife Olinda → Recife: 0 Recife → Olinda: 32,410 Total: 32,410 · 47% of the segment Norte Paulista → Recife: 27,826 Recife → Paulista: 127 Total: 27,953 · 50% of the segment Recife Paulista → Recife: 0 Recife → Paulista: 26,249 Total: 26,249 · 47% of the segment Sul Paulista → Recife: 0 Recife → Paulista: 655 Total: 655 · 1% of the segment Oeste Paulista → Recife: 0 Recife → Paulista: 857 Total: 857 · 2% of the segment Oeste Abreu e Lima → Igarassu: 45 Igarassu → Abreu e Lima: 0 Total: 45 · <1% of the segment Sul Abreu e Lima → Igarassu: 93 Igarassu → Abreu e Lima: 0 Total: 93 · <1% of the segment Recife Abreu e Lima → Igarassu: 3,685 Igarassu → Abreu e Lima: 0 Total: 3,685 · 18% of the segment Norte Abreu e Lima → Igarassu: 6,452 Igarassu → Abreu e Lima: 9,892 Total: 16,344 · 81% of the segment Norte Abreu e Lima → Paulista: 15,729 Paulista → Abreu e Lima: 7,961 Total: 23,690 · 77% of the segment Recife Abreu e Lima → Paulista: 0 Paulista → Abreu e Lima: 6,464 Total: 6,464 · 21% of the segment Sul Abreu e Lima → Paulista: 0 Paulista → Abreu e Lima: 176 Total: 176 · 1% of the segment Oeste Abreu e Lima → Paulista: 0 Paulista → Abreu e Lima: 606 Total: 606 · 2% of the segment Recife Cabo de Santo Agostinho → Jaboatão dos Guararapes: 0 Jaboatão dos Guararapes → Cabo de Santo Agostinho: 4,092 Total: 4,092 · 21% of the segment Sul Cabo de Santo Agostinho → Jaboatão dos Guararapes: 9,322 Jaboatão dos Guararapes → Cabo de Santo Agostinho: 6,085 Total: 15,407 · 79% of the segment Norte Cabo de Santo Agostinho → Jaboatão dos Guararapes: 0 Jaboatão dos Guararapes → Cabo de Santo Agostinho: 110 Total: 110 · 1% of the segment Norte Camaragibe → Recife: 207 Recife → Camaragibe: 1,167 Total: 1,374 · 3% of the segment Oeste Camaragibe → Recife: 20,576 Recife → Camaragibe: 0 Total: 20,576 · 47% of the segment Recife Camaragibe → Recife: 0 Recife → Camaragibe: 20,572 Total: 20,572 · 47% of the segment Sul Camaragibe → Recife: 0 Recife → Camaragibe: 1,384 Total: 1,384 · 3% of the segment Sul Camaragibe → São Lourenço da Mata: 473 São Lourenço da Mata → Camaragibe: 0 Total: 473 · 2% of the segment Recife Camaragibe → São Lourenço da Mata: 7,841 São Lourenço da Mata → Camaragibe: 0 Total: 7,841 · 32% of the segment Oeste Camaragibe → São Lourenço da Mata: 3,473 São Lourenço da Mata → Camaragibe: 11,815 Total: 15,288 · 63% of the segment Norte Camaragibe → São Lourenço da Mata: 441 São Lourenço da Mata → Camaragibe: 207 Total: 648 · 3% of the segment Norte Olinda → Paulista: 12,512 Paulista → Olinda: 12,110 Total: 24,622 · 100% of the segment Sul Cabo de Santo Agostinho → Ipojuca: 2,656 Ipojuca → Cabo de Santo Agostinho: 3,242 Total: 5,898 · 97% of the segment Recife Cabo de Santo Agostinho → Ipojuca: 194 Ipojuca → Cabo de Santo Agostinho: 0 Total: 194 · 3% of the segment Recife Igarassu → Itapissuma: 443 Itapissuma → Igarassu: 0 Total: 443 · 9% of the segment Norte Igarassu → Itapissuma: 1,908 Itapissuma → Igarassu: 2,502 Total: 4,410 · 91% of the segment Norte Ilha de Itamaracá → Itapissuma: 1,983 Itapissuma → Ilha de Itamaracá: 1,524 Total: 3,507 · 92% of the segment Recife Ilha de Itamaracá → Itapissuma: 0 Itapissuma → Ilha de Itamaracá: 300 Total: 300 · 8% of the segment Sul Jaboatão dos Guararapes → Moreno: 2,127 Moreno → Jaboatão dos Guararapes: 3,299 Total: 5,426 · 83% of the segment Recife Jaboatão dos Guararapes → Moreno: 1,132 Moreno → Jaboatão dos Guararapes: 0 Total: 1,132 · 17% of the segment Norte Paudalho → São Lourenço da Mata: 207 São Lourenço da Mata → Paudalho: 118 Total: 325 · 33% of the segment Oeste Paudalho → São Lourenço da Mata: 490 São Lourenço da Mata → Paudalho: 115 Total: 605 · 62% of the segment Recife Paudalho → São Lourenço da Mata: 0 São Lourenço da Mata → Paudalho: 43 Total: 43 · 4% of the segment Norte Araçoiaba → Paudalho: 207 Paudalho → Araçoiaba: 118 Total: 325 · 88% of the segment Recife Araçoiaba → Paudalho: 0 Paudalho → Araçoiaba: 43 Total: 43 · 12% of the segment Abreu e Lima Origin and destination (drawn): 18,457 Internal: 5,716 Araçoiaba Origin and destination (drawn): 368 Internal: 107 Cabo de Santo Agostinho Origin and destination (drawn): 23,523 Internal: 14,387 Camaragibe Origin and destination (drawn): 34,120 Internal: 16,039 Igarassu Origin and destination (drawn): 19,894 Internal: 6,108 Ipojuca Origin and destination (drawn): 6,092 Internal: 2,732 Ilha de Itamaracá Origin and destination (drawn): 3,807 Internal: 932 Itapissuma Origin and destination (drawn): 2,070 Internal: 215 Jaboatão dos Guararapes Origin and destination (drawn): 116,242 Internal: 49,538 Moreno Origin and destination (drawn): 6,558 Internal: 2,068 Olinda Origin and destination (drawn): 93,884 Internal: 43,046 Paudalho Origin and destination (drawn): 605 Paulista Origin and destination (drawn): 72,476 Internal: 32,361 Recife Origin and destination (drawn): 263,083 Internal: 397,353 São Lourenço da Mata Origin and destination (drawn): 23,593 Internal: 9,808 RecifeJaboatão dos GuararapesOlindaPaulistaCamaragibeCabo de Santo AgostinhoSão Lourenço da MataIgarassuAbreu e LimaIpojucaMorenoIlha de ItamaracáItapissumaPaudalhoAraçoiabaColour = categoryNorte 106kOeste 28kRecife 132kSul 77korigin and destinationinternal flow37% of the volume in 15 segments · 63% internal to the places

m$geojson is not the data behind the figure: it is the figure. Each feature is one paint operation (the casing of a corridor, a coloured line, the disc of a place), with its colour, its width and its place in the paint order. The widths are lengths on the ground, in the units of the input, so the drawing can be scaled with the map.

scene <- st_read(m$geojson, quiet = TRUE)
table(scene$kind)
#> 
#>          casing            halo        line_end line_end_casing            link 
#>              15              15              50              50              39 
#>     link_casing           place            ring          stroke 
#>              39              15              14              45

GeoJSON has no field for a projected coordinate system, and st_read() assumes longitude and latitude. The coordinates are those of the input, so the scene is given the CRS of the input and then reprojected:

scene <- st_set_crs(st_set_crs(scene, NA), rmr$crs)
scene <- st_transform(scene, 4326)
scene <- scene[order(scene$order),
               c("order", "kind", "width", "colour", "radius", "fill",
                 "stroke", "stroke_width", "label")]

Widths in metres

MapLibre measures a line width in pixels of the screen. A width on the ground becomes pixels through the scale of the map, which doubles with each zoom level: one pixel is about 78 271.5 × cos(latitude) / 2zoom metres. The expression below says that to MapLibre, so the figure grows and shrinks with the map; min_px keeps the lines visible when the whole region fits in the window.

latitude <- mean(st_bbox(scene)[c("ymin", "ymax")])
k <- 1 / (78271.517 * cos(latitude * pi / 180))
ground <- function(column, min_px = 0) {
  list("interpolate", list("exponential", 2), list("zoom"),
       0,  list("max", min_px, list("*", list("get", column), k)),
       22, list("max", min_px, list("*", list("get", column), k * 2^22)))
}

Under the names of the map

Layers added to a map go on top of it, and the flows would cover the names of the cities. A base map is itself a stack of layers: land, water, roads and buildings, and then the names (layers of type symbol) at the top. The figure goes between the two, just above the last layer that is not a name, so that it covers the roads and the map’s own names are written over the flows.

base <- carto_style("positron")
layers <- jsonlite::fromJSON(base, simplifyVector = FALSE)$layers
is_name <- vapply(layers, function(l) l$type == "symbol", logical(1))
first_label <- layers[[max(which(!is_name)) + 1]]$id
first_label
#> [1] "watername_ocean"

The layers, in paint order

The features come in the order in which they are painted: first the lines (casings, then colours), then the places. One MapLibre layer per run of features of the same type keeps that order; inside a layer, order sorts the features.

is_line <- as.vector(st_geometry_type(scene) == "LINESTRING")
runs <- rle(is_line)
last <- cumsum(runs$lengths)
first <- last - runs$lengths + 1

map <- maplibre(style = base, bounds = scene,
                projection = "mercator")
for (i in seq_along(last)) {
  part <- scene[first[i]:last[i], ]
  id <- paste0("milkflow-", i)
  map <- if (runs$values[i]) {
    add_line_layer(map, id, source = part,
                   line_color = get_column("colour"),
                   line_width = ground("width", min_px = 1.2),
                   line_join = "round", line_cap = "butt",
                   line_sort_key = get_column("order"),
                   before_id = first_label)
  } else {
    add_circle_layer(map, id, source = part,
                     circle_color = get_column("fill"),
                     circle_radius = ground("radius"),
                     circle_stroke_color = get_column("stroke"),
                     circle_stroke_width = ground("stroke_width"),
                     circle_sort_key = get_column("order"),
                     tooltip = "label", before_id = first_label)
  }
}
map

Zoom in on Recife: the lines keep their width on the ground, the order of the lines in each corridor is the one of the SVG, and the names of the cities stay readable over them. Point at a place for the name it has in the data.

Notes

  • A projected CRS. The input must be in planar coordinates, as always with milkflow, and you must know which: the GeoJSON carries the coordinates of the input and nothing else.
  • The schematic drawing is not a map. schematic = TRUE moves the places, so m$schematic_geojson is not georeferenced. With schematic_options = list(pin = TRUE) the places stay where they are and only the segments bend, and that scene can go on a map.
  • Saving. The map is an htmlwidget: htmlwidgets::saveWidget(map, "map.html") writes a page. It loads MapLibre and the base map from the network, unlike the page of write_html(), which needs none.
  • Other tools. write_geojson(m, "figure.geojson") writes the same scene to a file, for QGIS or any other program that reads GeoJSON.