Skip to contents

Aggregates, filters and routes origin-destination flows through a few shared corridors, in the style of a transit map, and draws the result as SVG (and, on request, TikZ, GeoJSON and an interactive HTML page). Optionally also computes a schematic (octilinear) layout, and splits each corridor into one line per category of the flows.

Usage

flowmap(
  nodes,
  flows,
  ...,
  skeleton = NULL,
  boundary = NULL,
  crs = NULL,
  units = NULL,
  group = FALSE,
  k = 3,
  filter = NULL,
  mu = 4,
  max_stretch = NULL,
  skeleton_source = c("delaunay", "input"),
  represent = c("all", "design"),
  schematic = FALSE,
  schematic_options = NULL,
  tikz = FALSE,
  html = FALSE,
  lines = c("auto", "off"),
  max_categories = 8,
  style = list(),
  id = "id",
  x = "x",
  y = "y",
  origin = "origin",
  destination = "destination",
  value = "value",
  category = NULL,
  label = NULL,
  weight = NULL,
  geojson = FALSE,
  aggregate = NULL
)

Arguments

nodes

A data frame of places, one row per node, with an id and planar coordinates; or an sf object of points in a projected CRS.

flows

A data frame of flows, one row per origin-destination pair (and category), with a non-negative value. Duplicate pairs are summed; flows from a node to itself count as internal.

...

Must be empty; the arguments after it must be named.

skeleton

Optional corridors given by the user: a data frame or matrix whose first two columns are node ids. Used with skeleton_source = "input"; its nodes without flows become junctions (see the section "Junctions").

boundary

Optional background outline, in the coordinates of the nodes: a two-column numeric matrix (one polyline), a list of them, or an sf/sfc object of lines or polygons.

crs, units

Optional text recorded in the output (e.g. "EPSG:31985", "m"). Taken from nodes when it is an sf object.

group

Aggregate the nodes into groups before routing: FALSE (no aggregation), the name of a column of nodes that holds the group of each node at some level (NA: the node stays alone), or TRUE (the column "group"). See the section "Groups and levels".

k

Pairs per place that design the corridors (the k largest outgoing and incoming); 0 uses every pair. Only for the default filter, "top_k".

filter

Optional filter of the pairs that design the corridors (see the section "Filters"): the name of a filter, e.g. "dominant", or a list with kind and its parameters, e.g. list(kind = "disparity", alpha = 0.01). NULL (default): the k largest pairs of each place.

mu

Weight of the detours against the ink, in units of a reference scale: larger values keep more segments.

max_stretch

Optional largest detour (path length over straight distance) allowed to a design pair.

skeleton_source

Where the corridors come from: the Delaunay triangulation of the places, pruned ("delaunay"), or skeleton ("input").

represent

Which pairs are drawn: all of them ("all") or only those that designed the corridors ("design").

schematic

Also compute the schematic (octilinear) layout. Runs of nodes with two segments (stations along a line) are laid out as one path between their ends, with the nodes set along it; the number of such chains is in x$schematic_spec$meta$params$schematic$chains. When no valid layout is found the geographic map still stands and the reason is in $schematic_error.

schematic_options

Optional named list of options of the schematic layout, passed to the core as a JSON object (an unknown name is an error): sector_slack (largest deviation of a port from the geographic direction, in sectors of 45 degrees, 0 to 4, default 1), fallback_slack (the slack tried when no layout satisfies sector_slack, with a warning; 0 to 4, default none), spacing (least distance between two nodes of average degree, as a fraction of the square root of the area per node, 0 to 4, default 0.5), bridge_cap (long segments are shortened to this many times the 90th percentile of the lengths; 0 never, or 1 to 100, default 1), spread (0 keeps the geography, 1 places the nodes by rank; 0 to 1, default 0) and the weights w_length, w_bend, w_bend_flow, w_displacement (0 to 1000; defaults 0.5, 3, 4, 1); and pin (TRUE keeps every node at its geographic position and only bends the segments to 0, 45 and 90 degrees, over the boundary: closer to the map, without the guarantees of the grid layout; default FALSE) and orthogonal (with pin = TRUE: horizontal and vertical pieces alone, no diagonals; default FALSE).

tikz

Also write the figures as TikZ pictures (a bare tikzpicture, for a LaTeX document that loads tikz), in $tikz and $schematic_tikz; see write_tikz().

html

Also write the interactive page (one self-contained HTML file, without network: the figures, a focus on each place, segment and line, and the numbers in tooltips), in $html; see write_html().

lines

"auto": one line per category when the flows have categories (see the section "Lines"); "off": ignore the categories.

max_categories

The largest number of categories, "other" included, from 1 to 64; the smallest categories beyond it are merged into "other".

style

A named list of drawing options passed to the core, e.g. list(title = "Commuting", theme = "dark", corners = "smooth"). See the section "Style" for the fields; unknown names are an error.

id, x, y

Column names in nodes (x and y are ignored for sf).

origin, destination, value

Column names in flows.

category

Optional column name in flows: the category of each flow (character, factor or numeric; NA means none). NULL uses the column "category" when it exists. See the section "Lines".

label, weight

Optional column names in nodes: the text drawn next to a place (default: its id) and the weight of a node when its group's position is averaged (default: its volume). NULL uses the columns "label" and "weight" when they exist.

geojson

Also write the figures as GeoJSON, in $geojson and $schematic_geojson: each paint operation of the figure in paint order, in the input's coordinates (reproject before using it as RFC 7946 longitude and latitude); places[].uses tells which segments and categories the flows of each place use. See write_geojson().

aggregate

Optional automatic aggregation (see the section "Automatic aggregation"): the number of places, e.g. 30, or a list with to, keep (ids of nodes never absorbed) and method ("ward", the default, or "gravity"), e.g. list(to = 30, keep = "2611606", method = "gravity"). NULL (default): none. Not with group.

Value

An object of class milkflow: a list with

spec

the drawing specification (FlowSpec), parsed with jsonlite::fromJSON(): nodes (with their kind, "place" or "junction"), segments, legend and meta (the parameters, the accounting, the metrics and the warnings);

svg

the corridor map, one SVG string;

schematic_spec, schematic_svg

the schematic layout and its SVG, or NULL;

schematic_error

why there is no schematic layout when one was asked for, or NULL;

tikz, schematic_tikz

the figures as TikZ pictures, with tikz = TRUE (and a schematic layout for the second), or NULL;

geojson, schematic_geojson

the figures as GeoJSON text (a FeatureCollection in the input's coordinates), with geojson = TRUE (and a schematic layout for the second), or NULL;

html

the interactive page, with html = TRUE, or NULL;

json

the output of the core, verbatim.

Errors of the core (unknown ids, non-finite values, bad options) are signalled as conditions of class milkflow_error; where the core names a flow or a node by its position, the message gives the row of flows or nodes (counted from 1). The warnings of the core are signalled as one warning of class milkflow_warning (see the section "Warnings").

Details

The pipeline is the one of the Rust core of the package (the crate 'milkflow', pipeline::run_json): the same input and options give the same bytes in R, in Rust and in the other bindings.

Filters

The corridors are designed by a subset of the pairs, chosen by a filter; the other pairs are then routed on those corridors (with represent = "all") or left out ("design"). Without filter, each place keeps its k largest outgoing and incoming pairs ("top_k"). filter is the name of a filter or a list with kind and its parameters:

"top_k"

the k largest pairs of each place, outgoing and incoming (list(kind = "top_k", k = 5); without k, the argument k; 0 keeps every pair);

"dominant"

the dominant flows of Nystuen and Dacey (1961): the largest flow of each place, when it goes to a larger place (size = the volume arriving there); a forest whose roots are the centres of the nodal regions;

"disparity"

the disparity backbone of Serrano, Boguna and Vespignani (2009): the pairs significant for their origin or their destination at level alpha (between 0 and 1, default 0.05);

"largest"

the n largest pairs (n required);

"share"

the largest pairs until they cover the fraction share (0 to 1, required) of the volume;

"threshold"

the pairs whose value is at least min (required).

The argument k only applies to "top_k": giving another k than the default next to another filter is an error. With filter, the parameters recorded in x$spec$meta$params hold the filter instead of k.

A sparse filter (any but "top_k") with represent = "all" routes every pair on corridors that only a few pairs designed: when the largest detour (x$spec$meta$metrics$stretch_max) is above 4, the core says so in a warning, which suggests represent = "design".

Groups and levels

With group, the nodes are merged into their groups before anything else: a group becomes one place, at the weighted centroid of its members, and the flows inside it become its internal volume. A node whose group is NA stays a place of its own.

group names a column of nodes. The same table can hold the groups of several nested levels (say a column district and a column region), and each call draws the level it names: flowmap(nodes, flows, group = "district"), then group = "region". The column is passed to the core as that level of the nodes' groups (in JSON, "groups": {"region": "Upland"} and the option "group": "region"), and x$spec$meta$params$group records the name of the level. At every level the accounting closes (total = routed + internal + filtered + unroutable); when the levels nest, the internal volume can only grow from a level to the coarser one. Nesting is not checked.

group = TRUE takes the column "group" and passes it as the single group field of the core's nodes (params$group is then TRUE): the figure is the same as with group = "group", only the parameters recorded differ.

Automatic aggregation

Without groups of your own, aggregate = 30 merges neighbouring places until 30 remain besides the isolated ones. The mass of a place is the volume that starts or ends at it (a flow from a place to itself counts at both ends). Neighbours are near: edges of the Delaunay triangulation of the places that are Gabriel edges (they do not jump over another place) and no longer than 4 times the median of those edges, contracted after each merge. Two methods choose each merge:

  • method = "ward" (the default) merges the pair of neighbouring groups of least m_a * m_b / (m_a + m_b) * d^2, m their masses and d the distance between their mass-weighted centroids: compact groups of similar weight, and two heavy places very close to each other (Recife and Olinda) merge early.

  • method = "gravity": the group of smallest mass joins the neighbouring group of largest mass / distance^2, the distance measured between the two representatives: heavy neighbouring places stay apart to the end, while the light interior becomes a few large groups.

A place without a near neighbour (an island, a capital of another state) stays alone and does not count in to; when no merge is left before to the call stops there. Both are reported in x$spec$meta$warnings, and the classes of width are then fitted to the segments between the other places. Each group is drawn at, and named after, its member of largest mass (its representative), so the map keeps real names at real places; the centroids only serve the choice. Ties are broken by mass and then by id, and the result does not depend on the order of the rows.

aggregate = list(to = 30, keep = c("2611606", "2607901")) protects the nodes of keep: they are never absorbed (they may absorb others, and then represent their group), and two of them never merge. to must be at least 1 and at least the number of nodes in keep. With to at least the number of places nothing is merged and the output is byte for byte that of a call without aggregate; otherwise x$spec$meta$params$aggregate records the option (with its method) and x$spec$meta$aggregation$members lists, for each place that stands for several nodes, their ids (the interactive page shows their names). As with group, the flows inside a group become its internal volume, the accounting closes and members counts the nodes. aggregate and group cannot be combined.

Both methods are spatial: they ignore who exchanges flow with whom. ward may, at an intermediate to, elect a minor centre as the representative of a compact piece of the interior; gravity keeps large neighbours apart and draws a small place into the heavy place near it even when its flows go elsewhere. There are no zoom levels: another to is another call.

Warnings

The core reports what it changed in the input without refusing it (repeated pairs summed, nodes at the same point merged, categories merged into "other", a schematic layout found only with a looser rule, long detours with a sparse filter, see "Filters") in x$spec$meta$warnings (and x$schematic_spec$meta$warnings). flowmap() signals them once, as one R warning of class milkflow_warning (one line per warning of the core), and print() lists them again; flowmap_json() and new_milkflow() never warn.

Coordinates

Coordinates must be planar (projected), in a unit such as metres: the core measures lengths with Euclidean distance. Longitude and latitude are refused when nodes is an sf object; with a plain data frame it is up to the caller (project first, e.g. with sf::st_transform()).

Accounting

Every unit of flow ends in exactly one bucket: drawn in a corridor (routed), inside a place or group (internal), left out by the filter (filtered) or without a path in the skeleton (unroutable). The print method reports the shares; the numbers are in x$spec$meta$accounting.

Lines (categories)

When the flows have a category (category, by default the column "category" when there is one) and lines = "auto", each segment is split into one line per category that crosses it, as on a transit map: the core orders the lines along the corridors so that they cross as little as possible, and continues each line from one segment to the next. At most max_categories categories are kept, "other" included: the smallest ones, and the flows without a category (NA or ""), go to "other". The routing, the accounting and the width classes do not change: the lines are a finer account of the same corridors.

The lines are returned in the specification, as two data frames:

x$spec$legend$categories

one row per category: id (the category, "" for "other"), label and total (the volume drawn in corridors);

x$spec$lines

one row per line of a segment, the long format: segment (the id of the segment in x$spec$segments), position (1 is the leftmost line for a traveller going from end a to end b of the segment), category and label (as in the legend), flow_ab, flow_ba (the volume of the category in each direction), next_a, next_b: list columns with the ids of the segments the line continues into at end a and at end b (empty where it ends), and ends_a, ends_b: the volume of the line whose pairs start or end at end a / end b (0 where everything goes through; a line may both continue and stop at a place).

Without categories, or with lines = "off", both are NULL and the output is the one of a run without categories.

The SVG figure and the interactive page draw the lines: each segment becomes a bundle of parallel lines, one colour per category (a palette safe for colour-blind readers, "other" in grey), joined from one segment to the next at the nodes, with a legend of the categories. The style fields lines, line_width and line_colours (section "Style") control them; style = list(lines = "off") draws the corridors as one band while keeping the lines in the specification. The TikZ figure is drawn from the same scene as the SVG, lines included (see write_tikz()). x$spec$meta$metrics$line_crossings counts the crossings of the lines at the nodes.

Junctions

With skeleton_source = "input" (corridors given by the user, such as a road or transit network), the network may have nodes where no flow starts or ends: crossroads and forks. A node of the user's skeleton with no flow of its own and at least one drawn segment is a junction: its kind in x$spec$nodes is "junction" (otherwise "place"), its size, internal volume and residuals are 0, and the figures draw it as a small dot, never as a place, and without a label. x$spec$meta$metrics$junctions counts them (absent without junctions). With the Delaunay skeleton every node is a place.

Style

style is a named list passed to the core as a JSON object; every field is optional and an unknown name is an error that lists the fields the core knows. Lengths are SVG pixels; the canvas and the symbols are then fitted to each drawing. The TikZ figure follows the same style (it is drawn from the same scene as the SVG). Colours are "#RRGGBB" (or any SVG colour; the TikZ figure needs "#RRGGBB" or "#RGB" and otherwise takes the theme's colour, with a note in the picture). The fields of this version:

title

text above the map (default none);

theme

colour scheme: "light" (default), "dark", "print" (greys only) or "basemap" (no background, to lay over a base map);

palette

a named accent tuned to the theme: "red", "blue", "green", "amber", "purple" or "graphite" (default: the theme's own accent);

accent, background

explicit colours of the corridors and of the paper (also halos and casings); they win over theme and palette;

corridor_opacity

opacity of the corridors, as one group (default 1, or 0.85 with "basemap");

context_opacity

opacity of the boundary (default 1);

directions

"sum" (default: one band per segment, as wide as the class of its total) or "split" (one lane per direction, keeping to the right);

direction_colours

with directions = "split", one colour per direction (towards / away from the main place) instead of the accent (default FALSE);

stroke

"solid" (default) or "rails" (class c drawn as c + 1 thin parallel rails; not combined with split lanes);

rail_width, rail_gap, max_rails

width of a rail (default 1.6, positive), gap between rails (1.5, at least 0) and the largest number of rails (8, at least 1);

corners

"round" (default), "mitre" (mitred joins, square junctions) or "smooth" (the bends inside a segment's path become arcs) or "bevel" (the bends are cut by a straight piece);

corner_radius

radius of the bends with corners = "smooth", size of the cut with "bevel" (default 12, at least 0);

fade

fading by volume, 0 to 0.9 (default 0): the segments fade towards the paper, the largest not at all;

place_shape

symbol of a place: "circle" (default) or "square";

exits

with frame_on_boundary, how a segment cut at the edge of the map ends past the boundary: "fade" (default, each line fades into the paper), "dashed" (each line goes on dashed) or "arrow" (an arrowhead);

class_widths

stroke width of each width class, thinnest first (default c(1.5, 3, 5.5, 9, 14)); always sent as an array;

radius_min, radius_max

radius of the smallest and of the largest place (default 3 and 11);

font_size

size of an ordinary label (default 11; in TikZ, scaled with the picture, in the sans-serif family of the document);

max_labels, key_labels

how many places get a label (default 30), by decreasing volume, and how many of the first ones may get a leader line when there is no room next to the place (default 12);

width, height, margin

the canvas the fitting starts from (default 900 by 700, at most; margin 40);

frame_on_boundary

frame the map on the boundary alone, so that the region fills the canvas even when some places lie far outside it (default FALSE). Nothing is cut silently: the places outside the frame are not drawn and the honesty line counts them ("2 places off the map"), and a segment towards one of them is cut at the edge of the map and ends there as exits says;

lines

in the lines mode, "auto" (default) draws one line per category, "off" the corridors as one band (the lines stay in the specification);

line_width

width of the lines: "fixed" (default: every line as wide as the second width class, so that a corridor is as wide as its number of lines, as on a metro map) or "flow" (the width of the corridor's class shared among its lines by their volume);

line_colours

the colour of each category's line, in the order of x$spec$legend$categories, as "#RRGGBB" or "#RGB" (anything else is an error); the categories beyond the vector take the palette; always sent as an array;

lang

the language of the fixed texts of the SVG figure and of the page and of the TikZ figure (legend, honesty line, tooltips, number format): "pt" (Brazilian Portuguese, default), "en", "es" or "fr".

Later versions of the core may add fields; the R side does not keep a list of them, so they work here as soon as the core knows them. A value of length one is a JSON scalar, a longer vector an array.

Examples

m <- flowmap(demo_nodes, demo_flows, style = list(title = "Commuting"))
m
#> <milkflow> 24 places (from 24 nodes), 25 segments, 5 width classes
#> Volume: 88,974 in 180 pairs (180 routed)
#>   in corridors    98.1%
#>   internal         1.9%
#>   filtered out     0.0%
#>   without a path   0.0%
#> Lines: 3 categories on 25 segments, 129 crossings at nodes
#>   leisure  14.8% of the drawn volume
#>   study    24.0% of the drawn volume
#>   work     61.3% of the drawn volume
#> Detour: mean 1.10, max 5.09
# The share of the volume drawn in corridors:
m$spec$meta$accounting$routed / m$spec$meta$accounting$total
#> [1] 0.9814553

# demo_flows has a column "category" (trip purpose): one line per purpose.
m$spec$legend$categories
#>        id   label total
#> 1 leisure leisure 12883
#> 2   study   study 20919
#> 3    work    work 53522
head(m$spec$lines)
#>   segment position category   label flow_ab flow_ba  next_a next_b ends_a
#> 1       0        1     work    work    3341    2645 1, 2, 3      6   4356
#> 2       0        2    study   study    1603     681 1, 2, 3      6   1616
#> 3       0        3  leisure leisure     613     699 1, 2, 3      6    984
#> 4       1        1  leisure leisure     296     630 0, 2, 3      5    530
#> 5       1        2    study   study     467     627 0, 2, 3      5    583
#> 6       1        3     work    work    2042     953 0, 2, 3      5   1924
#>   ends_b
#> 1   1544
#> 2    878
#> 3    395
#> 4     13
#> 5    277
#> 6    544
# Ignore the categories, and draw with another theme and palette.
d <- flowmap(demo_nodes, demo_flows, lines = "off",
             style = list(theme = "dark", palette = "amber", corners = "smooth"))
d
#> <milkflow> 24 places (from 24 nodes), 25 segments, 5 width classes
#> Volume: 88,974 in 180 pairs (180 routed)
#>   in corridors    98.1%
#>   internal         1.9%
#>   filtered out     0.0%
#>   without a path   0.0%
#> Detour: mean 1.10, max 5.09

# Aggregate the towns by district and keep fewer corridors.
g <- flowmap(demo_nodes, demo_flows, group = "district", mu = 1)
g
#> <milkflow> 3 places (from 24 nodes), 2 segments, 1 width classes
#> Volume: 88,974 in 6 pairs (6 routed)
#>   in corridors    11.0%
#>   internal        89.0%
#>   filtered out     0.0%
#>   without a path   0.0%
#> Lines: 3 categories on 2 segments, 0 crossings at nodes
#>   leisure  14.2% of the drawn volume
#>   study    25.1% of the drawn volume
#>   work     60.7% of the drawn volume
#> Detour: mean 1.18, max 1.89
# A coarser level of the same towns: two regions.
towns <- demo_nodes
towns$region <- ifelse(towns$district == "Coast", "Shore", "Upland")
r <- flowmap(towns, demo_flows, group = "region")
c(district = g$spec$meta$accounting$internal, region = r$spec$meta$accounting$internal)
#> district   region 
#>    79143    81131 

# Without groups: merge the towns by proximity into 6 places, Enlor kept.
a <- flowmap(demo_nodes, demo_flows, aggregate = list(to = 6, keep = "T20"))
a$spec$meta$aggregation$members
#> $T01
#> $T01[[1]]
#> [1] "T01"
#> 
#> $T01[[2]]
#> [1] "T02"
#> 
#> $T01[[3]]
#> [1] "T03"
#> 
#> $T01[[4]]
#> [1] "T04"
#> 
#> $T01[[5]]
#> [1] "T05"
#> 
#> $T01[[6]]
#> [1] "T06"
#> 
#> $T01[[7]]
#> [1] "T07"
#> 
#> $T01[[8]]
#> [1] "T08"
#> 
#> $T01[[9]]
#> [1] "T09"
#> 
#> 
#> $T10
#> $T10[[1]]
#> [1] "T10"
#> 
#> $T10[[2]]
#> [1] "T15"
#> 
#> $T10[[3]]
#> [1] "T17"
#> 
#> 
#> $T13
#> $T13[[1]]
#> [1] "T11"
#> 
#> $T13[[2]]
#> [1] "T13"
#> 
#> 
#> $T16
#> $T16[[1]]
#> [1] "T12"
#> 
#> $T16[[2]]
#> [1] "T14"
#> 
#> $T16[[3]]
#> [1] "T16"
#> 
#> 
#> $T18
#> $T18[[1]]
#> [1] "T18"
#> 
#> $T18[[2]]
#> [1] "T19"
#> 
#> $T18[[3]]
#> [1] "T22"
#> 
#> 
#> $T20
#> $T20[[1]]
#> [1] "T20"
#> 
#> $T20[[2]]
#> [1] "T21"
#> 
#> $T20[[3]]
#> [1] "T23"
#> 
#> $T20[[4]]
#> [1] "T24"
#> 
#> 

# Corridors designed by the dominant flows only, figure in English.
n <- flowmap(demo_nodes, demo_flows, filter = "dominant", style = list(lang = "en"))
n$spec$meta$params$filter
#> $kind
#> [1] "dominant"
#> 
flowmap(demo_nodes, demo_flows, filter = list(kind = "share", share = 0.8),
        represent = "design")
#> <milkflow> 24 places (from 24 nodes), 22 segments, 5 width classes
#> Volume: 88,974 in 180 pairs (52 routed)
#>   in corridors    78.6%
#>   internal         1.9%
#>   filtered out    19.5%
#>   without a path   0.0%
#> Lines: 3 categories on 22 segments, 9 crossings at nodes
#>   leisure  14.7% of the drawn volume
#>   study    23.6% of the drawn volume
#>   work     61.6% of the drawn volume
#> Detour: mean 1.01, max 1.94

# Other column names.
trips <- data.frame(from = "A", to = c("B", "C"), n = c(10, 4))
towns <- data.frame(code = c("A", "B", "C"), east = c(0, 10, 4), north = c(0, 0, 8))
flowmap(towns, trips, id = "code", x = "east", y = "north",
        origin = "from", destination = "to", value = "n")
#> <milkflow> 3 places (from 3 nodes), 2 segments, 2 width classes
#> Volume: 14 in 2 pairs (2 routed)
#>   in corridors   100.0%
#>   internal         0.0%
#>   filtered out     0.0%
#>   without a path   0.0%
#> Detour: mean 1.00, max 1.00

# \donttest{
s <- flowmap(demo_nodes, demo_flows, schematic = TRUE, tikz = TRUE, html = TRUE,
             schematic_options = list(sector_slack = 2))
is.null(s$schematic_svg)
#> [1] FALSE
substr(s$tikz, 1, 80)
#> [1] "% milkflow 0.1 TikZ figure (geographic): 14.00 x 12.79 cm, 24 places, 25 segment"
nchar(s$html)
#> [1] 305092
# }
if (interactive()) plot(m)