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 NorteThe 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"))
mm$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 45GeoJSON 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.
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)
}
}
mapZoom 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 = TRUEmoves the places, som$schematic_geojsonis not georeferenced. Withschematic_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 ofwrite_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.