Links between FromStep and ToStep

How are the nodes connected, and which are central?

Twenty-two hand-offs between the twelve steps of an order fulfilment process, from order received to delivered, each with the team that owns the step it starts from and the number of orders that took that path. Backorders, cancellations, rework and returns loop back or leave the main line, so it is a real process rather than a straight chain. A from-step, a to-step and a team make a flowchart with a swimlane per team.

Order Fulfilment Process Flow: 22 rows, 4 columns. Download the CSV

The first 10 rows
FromStepToStepTeamSum of Orders
Order receivedStock checkReceiving8150
Order receivedBackorderReceiving280
Order receivedCancelledReceiving170
Stock checkPickReceiving8080
Stock checkBackorderReceiving690
Stock checkCancelledReceiving80
BackorderStock checkReceiving700
BackorderPickReceiving260
BackorderCancelledReceiving130
PickPackWarehouse8180
A network diagram of the "Order Fulfilment Process Flow" dataset: 12 nodes joined by 22 links, each one a connection in the data.
A network diagram of the "Order Fulfilment Process Flow" dataset: 12 nodes joined by 22 links, each one a connection in the data.

How to read it

Positions come from a simulation that pulls linked nodes together, so distance means little and links mean everything. Backorder has the most links, 6.

The chart's code (20 KB of JavaScript, D3)

It carries its own copies of these helpers: llmText, llmFrameTween, llmRangeBrush, llmSlider, llmNumberEntry, llmSegmented, llmPredictor, llmResponseCurves, llmTerritories, llmCutoff, llmContrast, llmSurvival, llmModelFormat, llmSubgroups, llmSegments, llmGlyphs, llmBreadcrumb, llmKeyframes, llmScrubber, llmValueColumn, llmValueRamp, llmFitLabel, llmThinLabels, llmFitAxisTicks, llmSymlog, llmClipOutliers, llmGeoZoom, llmGeoPointNotes, llmMapLabels, llmGeoMarks, llmPlaceUnit, llmWorldFit, llmRegionFit, llmFlowKey, llmFlowArcs, llmFrameFill, llmTooltip, llmSwarm, llmKde, llmOrbit3d, llmBoundedScale, llmBivariate, llmLegendLayout, llmPager, llmTableFrame, llmGrid, llmUtcDays, llmPeriodGrid, llmTileGrid, llmMermaid, llmDecomp, llmTopN, llmFlipDeck, llmFilterScope, llmDisplayName, llmThemeColors, llmWordCloud.

// bic:keyboard-marks
d3.llmTooltip = function (container, opts) {
opts = opts || {};
var gap = opts.gap == null ? 12 : opts.gap;    // distance from the cursor
var edge = opts.edge == null ? 4 : opts.edge;  // minimum distance from the container edge
var routed = false;                            // true while the HOST is showing our content
var lastContent = '';                          // what to re-send if the host is driving
var lastEv = null;                             // where the cursor last was, for a re-fit

var host = (container && typeof container.node === 'function') ? container.node() : container;
var noop = { show: function () { return this; }, move: function () { return this; }, hide: function () { return this; },
html: function () { return this; }, text: function () { return this; }, node: null };
if (!host || !host.appendChild) return noop;

var mount = host;
if (mount.tagName && String(mount.tagName).toLowerCase() === 'svg' && mount.parentNode) {
mount = mount.parentNode;
}
if (!mount || !mount.appendChild) return noop;

try {
var pos = (typeof getComputedStyle === 'function') ? getComputedStyle(mount).position : '';
if (!pos || pos === 'static') mount.style.position = 'relative';
} catch (e) { /* jsdom / exec-gate: no layout engine, positioning is inert anyway */ }

var tip = mount.__llmTip;
if (!tip || tip.parentNode !== mount) {
tip = document.createElement('div');
tip.className = 'llm-tooltip';
tip.style.position = 'absolute';
tip.style.left = '0px';
tip.style.top = '0px';
tip.style.pointerEvents = 'none';
tip.style.visibility = 'hidden';
tip.style.zIndex = '20';
tip.style.boxSizing = 'border-box';
tip.style.whiteSpace = opts.wrap ? 'normal' : 'nowrap';
tip.style.background = 'rgba(255,255,255,0.97)';
tip.style.border = '1px solid rgba(0,0,0,0.28)';
tip.style.borderRadius = '4px';
tip.style.padding = '6px 9px';
tip.style.boxShadow = '0 2px 6px rgba(0,0,0,0.22)';
tip.style.color = '#222';
tip.style.fontSize = '12px';
mount.appendChild(tip);
mount.__llmTip = tip;
}

function hostTip() {
try {
var n = mount, guard = 0;
while (n && guard++ < 8) {
if (n.__lchHostTip && typeof n.__lchHostTip.show === 'function') return n.__lchHostTip;
n = n.parentNode;
}
} catch (e) { /* detached node / cross-document parent */ }
return null;
}

function metrics() {
var w = 0, h = 0, cw = 0, ch = 0;
try {
var r = mount.getBoundingClientRect();
cw = r.width; ch = r.height;
} catch (e) { /* fall through to the client* fallbacks */ }
if (!cw) cw = mount.clientWidth || 0;
if (!ch) ch = mount.clientHeight || 0;
w = tip.offsetWidth || 0;
h = tip.offsetHeight || 0;
return { w: w, h: h, cw: cw, ch: ch };
}

function local(ev) {
var x = 0, y = 0;
try {
var r = mount.getBoundingClientRect();
if (ev && ev.clientX != null) { x = ev.clientX - r.left; y = ev.clientY - r.top; }
} catch (e) {
if (ev && ev.clientX != null) { x = ev.clientX; y = ev.clientY; }
}
return { x: x, y: y };
}

function place(ev) {
var m = metrics();
if (!m.cw || !m.ch) return;              // no layout to clamp against (exec gate)
var p = local(ev);

var left = p.x + gap;
if (left + m.w > m.cw - edge) left = p.x - gap - m.w;
if (left < edge) left = edge;
if (left + m.w > m.cw - edge) left = Math.max(edge, m.cw - m.w - edge);

var top = p.y + gap;
if (top + m.h > m.ch - edge) top = p.y - gap - m.h;
if (top < edge) top = edge;
if (top + m.h > m.ch - edge) top = Math.max(edge, m.ch - m.h - edge);

tip.style.left = Math.round(left) + 'px';
tip.style.top = Math.round(top) + 'px';
}

function looksLikeEvent(x) {
return !!x && typeof x === 'object' && !Array.isArray(x)
&& (typeof x.clientX === 'number' || typeof x.type === 'string' || ('target' in x));
}

function setContent(content, asText) {
if (Array.isArray(content)) content = content.map(function (x) { return x == null ? '' : String(x); }).join(asText ? ' ' : '<br/>');
lastContent = content == null ? '' : String(content);
if (!asText && typeof content === 'string' && content.indexOf('<') >= 0) tip.innerHTML = lastContent;
else tip.textContent = lastContent;
}

function setAndRefit(self, content, asText) {
setContent(content, asText);
if (routed) {
var hbSet = hostTip();
if (hbSet && hbSet.show(lastContent, lastEv) === true) return self;
routed = false;                          // the host let go: the tooltip is still on screen, so draw ours
return self.show(null, lastEv);
}
if (tip.style.visibility === 'visible') return self.show(null, lastEv);
return self;
}

return {
node: tip,
html: function (content) { return arguments.length ? setAndRefit(this, content, false) : lastContent; },
text: function (content) { return arguments.length ? setAndRefit(this, content, true) : (tip.textContent || ''); },
show: function (content, ev) {
if (looksLikeEvent(content) && !looksLikeEvent(ev)) { var swapped = content; content = ev; ev = swapped; }
if (ev) lastEv = ev;
if (content != null) setContent(content, false);
tip.style.maxWidth = 'none';
tip.style.visibility = 'visible';      // measurable BEFORE placing
var m = metrics();
if (m.ch && m.h + (2 * edge) > m.ch) {
var hbShow = hostTip();
if (hbShow && hbShow.show(lastContent, ev) === true) {
routed = true;
tip.style.visibility = 'hidden';
return this;
}
}
routed = false;
if (m.cw) tip.style.maxWidth = Math.max(80, m.cw - (2 * edge)) + 'px';
place(ev);
return this;
},
move: function (ev) {
if (ev) lastEv = ev;
if (routed) { var hbMove = hostTip(); if (hbMove) hbMove.move(ev); return this; }
if (tip.style.visibility === 'visible') place(ev);
return this;
},
hide: function () {
if (routed) { var hbHide = hostTip(); if (hbHide) hbHide.hide(); routed = false; }
tip.style.visibility = 'hidden';
return this;
}
};
};
d3.llmThemeColors = function (options) {
options = options || {};
var pick = function (v, d) { return (typeof v === 'string' && v && v !== 'transparent') ? v : d; };
var bg = pick(options.backgroundColor, pick(options.themeBg, '#ffffff'));
var fg = pick(options.themeFg, '#252423');
var hc = !!options.isHighContrast;
var pal = (options.palette && options.palette.length) ? options.palette.slice() : ['#4C78A8', '#F58518', '#54A24B', '#E45756', '#72B7B2', '#B279A2', '#FF9DA6', '#9D755D'];
var rgb = function (c) { var x = null; try { x = d3.rgb(c); } catch (e) { x = null; } return x && isFinite(x.r) ? x : d3.rgb(128, 128, 128); };
var lum = function (c) {
var r = rgb(c);
var f = function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r.r) + 0.7152 * f(r.g) + 0.0722 * f(r.b);
};
var contrast = function (a, b) { var x = lum(a) + 0.05, y = lum(b) + 0.05; return x > y ? x / y : y / x; };
var legible = function (col, floor) {
floor = floor || 3;
var c = d3.lab(rgb(col));
var step = lum(bg) > 0.5 ? -3 : 3;   // a light background darkens the hue, a dark one lightens it
for (var i = 0; i < 34 && contrast(c.formatHex(), bg) < floor; i++) c.l = Math.max(0, Math.min(100, c.l + step));
return c.formatHex();
};
var good = hc ? pick(options.themeAccent, fg) : legible('#2e7d32');
var bad = hc ? fg : legible('#c62828');
var slot = function (value, n) {
var h = 2166136261, text = String(value);
for (var i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h % n;
};
var deltaE2000 = function (x, y) {
var rad = Math.PI / 180, L1 = x.l, a1 = x.a, b1 = x.b, L2 = y.l, a2 = y.a, b2 = y.b;
var C1 = Math.sqrt(a1 * a1 + b1 * b1), C2 = Math.sqrt(a2 * a2 + b2 * b2), Cm = (C1 + C2) / 2;
var G = 0.5 * (1 - Math.sqrt(Math.pow(Cm, 7) / (Math.pow(Cm, 7) + Math.pow(25, 7))));
var a1p = (1 + G) * a1, a2p = (1 + G) * a2;
var C1p = Math.sqrt(a1p * a1p + b1 * b1), C2p = Math.sqrt(a2p * a2p + b2 * b2);
var hp = function (bb, ap) { if (bb === 0 && ap === 0) return 0; var hh = Math.atan2(bb, ap) / rad; return hh < 0 ? hh + 360 : hh; };
var h1p = hp(b1, a1p), h2p = hp(b2, a2p);
var dLp = L2 - L1, dCp = C2p - C1p, dhp = 0;
if (C1p * C2p !== 0) { dhp = h2p - h1p; if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360; }
var dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhp * rad / 2);
var Lm = (L1 + L2) / 2, Cmp = (C1p + C2p) / 2, hm = h1p + h2p;
if (C1p * C2p !== 0) { if (Math.abs(h1p - h2p) > 180) hm += (hm < 360 ? 360 : -360); hm /= 2; }
var T = 1 - 0.17 * Math.cos((hm - 30) * rad) + 0.24 * Math.cos(2 * hm * rad) + 0.32 * Math.cos((3 * hm + 6) * rad) - 0.2 * Math.cos((4 * hm - 63) * rad);
var dTh = 30 * Math.exp(-Math.pow((hm - 275) / 25, 2));
var Rc = 2 * Math.sqrt(Math.pow(Cmp, 7) / (Math.pow(Cmp, 7) + Math.pow(25, 7)));
var Sl = 1 + 0.015 * Math.pow(Lm - 50, 2) / Math.sqrt(20 + Math.pow(Lm - 50, 2)), Sc = 1 + 0.045 * Cmp, Sh = 1 + 0.015 * Cmp * T;
var Rt = -Math.sin(2 * dTh * rad) * Rc;
var tl = dLp / Sl, tc = dCp / Sc, th = dHp / Sh;
return Math.sqrt(tl * tl + tc * tc + th * th + Rt * tc * th);
};
var order = null, pool = null, near = null;
var growOrder = function (count) {
if (!order) {
order = pal.map(function (c) { return rgb(c).formatHex(); });
var taken = order.map(function (c) { return d3.lab(c); });
var seenHex = {};
order.forEach(function (c) { seenHex[c] = 1; });
pool = [];
pal.forEach(function (c) {
var h = d3.hcl(rgb(c));
if (!isFinite(h.h)) h.h = 0;
var chroma = Math.max(isFinite(h.c) ? h.c : 0, 35);
[h.l, 38, 52, 66].forEach(function (L) {
for (var k = 1; k < 18; k++) {
var cc = d3.hcl((h.h + k * 20) % 360, chroma, L);
while (!cc.displayable() && cc.c > 20) cc.c -= 5;
if (!cc.displayable()) continue;
var hl = d3.hsl(cc).l;
if (!(hl > 0.15 && hl < 0.85)) continue;
var hx = cc.formatHex();
if (seenHex[hx]) continue;
seenHex[hx] = 1;
pool.push({ hex: hx, lab: d3.lab(hx) });
}
});
});
near = pool.map(function (q) {
var m = Infinity;
for (var t = 0; t < taken.length; t++) m = Math.min(m, deltaE2000(q.lab, taken[t]));
return m;
});
}
while (order.length < count && pool.length) {
var best = 0;
for (var q = 1; q < pool.length; q++) if (near[q] > near[best]) best = q;
var picked = pool.splice(best, 1)[0];
near.splice(best, 1);
order.push(picked.hex);
for (var r2 = 0; r2 < pool.length; r2++) near[r2] = Math.min(near[r2], deltaE2000(pool[r2].lab, picked.lab));
}
for (var round = 1; order.length < count && round < 40; round++) {
for (var e = 0; e < pal.length && order.length < count; e++) {
var hc = d3.hsl(pal[e]);
if (!isFinite(hc.h)) hc.h = 0;
var step = Math.ceil(round / 2) * 0.12 * (round % 2 ? 1 : -1);
hc.l = Math.max(0.12, Math.min(0.88, hc.l + step));
hc.h = (hc.h + round * 7) % 360;
var cx = hc.formatHex();
if (order.indexOf(cx) < 0) order.push(cx);
}
}
};
var extended = function (count) {
if (pal.length >= count) return pal.slice();
growOrder(count);
return pal.slice().concat(order.slice(pal.length, count));
};
var memory = function () {
var m = d3.__lchCategorySlots;
if (!m || !Array.isArray(m.groups)) { m = { groups: [] }; try { d3.__lchCategorySlots = m; } catch (e) { /* a frozen d3: no memory */ } }
return m;
};
var categories = function (values) {
var seen = {}, list = [];
(values || []).forEach(function (v) { var k = v === null || v === undefined ? '' : String(v); if (!seen[k]) { seen[k] = 1; list.push(k); } });
list.sort();
var mem = memory(), group = null, best = 0;
mem.groups.forEach(function (g) {
var shared = 0;
list.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(g.slots, k)) shared++; });
if (shared > best) { best = shared; group = g; }
});
if (!group) {
group = { slots: {}, used: {}, size: 0 };
mem.groups.push(group);
if (mem.groups.length > 32) mem.groups.shift();
}
var fresh = list.filter(function (k) { return !Object.prototype.hasOwnProperty.call(group.slots, k); });
var total = group.size + fresh.length;
var cols = extended(Math.max(list.length, total));
var n = cols.length;
fresh.forEach(function (k) {
if (group.size >= 2000) return;   // a category this long is not a palette's job: past it, a value is placed but not remembered
var i = 0;
while (group.used[i] && i < n) i++;
group.used[i] = 1;
group.slots[k] = i;
group.size++;
});
var map = {};
list.forEach(function (k) {
var i = Object.prototype.hasOwnProperty.call(group.slots, k) ? group.slots[k] : slot(k, n);
if (i >= cols.length) cols = extended(i + 1);
map[k] = cols[i % cols.length];
});
return function (v) {
var k = v === null || v === undefined ? '' : String(v);
return map[k] || cols[slot(k, n)];
};
};
return { bg: bg, fg: fg, good: good, bad: bad, categories: categories, legible: function (c) { return legible(c); }, contrast: contrast, palette: pal };
};


function render(container, data, options) {
  container.replaceChildren();
  const W = options.width, H = options.height;
  const fg = options.themeFg || 'currentColor';
  const bg = options.themeBg || '#fff';
  const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  const cols = data.columns.map(c => c.name);
  const iF = cols.indexOf('FromStep'), iT = cols.indexOf('ToStep'), iM = cols.indexOf('Team'), iV = cols.indexOf('Sum of Orders');
  [['FromStep', iF], ['ToStep', iT], ['Team', iM], ['Sum of Orders', iV]].forEach(p => {
    if (p[1] < 0) throw new Error('INVALID:column "' + p[0] + '" not found');
  });
  const nf = new Intl.NumberFormat(options.cultureCode, { maximumFractionDigits: 0 });
  const emptyMsg = (options.noDataText && typeof options.noDataText === 'string') ? options.noDataText : 'No data to display';

  // aggregate edges by from|to|team
  const emap = new Map();
  let skipped = 0;
  data.rows.forEach((r, i) => {
    const v = r[iV];
    if (v == null || !isFinite(+v) || +v <= 0 || r[iF] == null || r[iT] == null) { skipped++; return; }
    const k = r[iF] + '\u0001' + r[iT] + '\u0001' + r[iM];
    if (!emap.has(k)) emap.set(k, { source: String(r[iF]), target: String(r[iT]), team: r[iM], value: 0, rows: [] });
    const e = emap.get(k); e.value += +v; e.rows.push(i);
  });
  const links = [...emap.values()];
  if (!links.length) {
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('fill', fg).attr('font-size', 12).text(emptyMsg);
    return;
  }
  const nodeMap = new Map();
  const addNode = id => { if (!nodeMap.has(id)) nodeMap.set(id, { id, rows: new Set(), tot: 0 }); return nodeMap.get(id); };
  links.forEach(l => {
    const a = addNode(l.source), b = addNode(l.target);
    l.rows.forEach(i => { a.rows.add(i); b.rows.add(i); });
    a.tot += l.value; b.tot += l.value;
  });
  const nodes = [...nodeMap.values()];
  nodes.forEach(n => { n.rowIdx = [...n.rows].sort((a, b) => a - b).join(','); });
  const teams = [...new Set(data.rows.map(r => r[iM]))];
  const T = d3.llmThemeColors(options);
  const byTeam = T.categories(teams);
  const colorOf = t => T.legible(byTeam(t));
  const teamRows = new Map(teams.map(t => [t, []]));
  data.rows.forEach((r, i) => teamRows.get(r[iM]).push(i));

  // layout regions
  const showLegend = teams.length >= 2;
  const widest = d3.max(teams, t => String(t).length * 7) || 60;
  let legendW = 0, topBand = 0;
  if (showLegend) {
    if (W >= 500) legendW = Math.max(96, Math.min(W * 0.3, widest + 40));
    else topBand = 44;
  }
  const pad = 10;
  const plotX0 = pad, plotX1 = W - legendW - pad;
  const plotY0 = topBand + pad, plotY1 = H - 30;

  const maxTot = d3.max(nodes, n => n.tot) || 1;
  const rScale = d3.scaleSqrt().domain([0, maxTot]).range([3, 15]);
  const maxV = d3.max(links, l => l.value) || 1;
  const wScale = d3.scaleSqrt().domain([0, maxV]).range([0.8, 9]);
  nodes.forEach(n => { n.r = rScale(n.tot); n.lw = n.id.length * 6 + 6; });

  const N = nodes.length;
  nodes.forEach((n, i) => {
    const a = (i / N) * 2 * Math.PI;
    n.x = W / 2 + Math.cos(a) * 100; n.y = H / 2 + Math.sin(a) * 100;
  });
  const pw = plotX1 - plotX0, ph = plotY1 - plotY0;
  const strength = N <= 12 ? -Math.max(450, pw / 2) : -Math.max(300, pw / 4);
  const sim = d3.forceSimulation(nodes)
    .force('link', d3.forceLink(links).id(d => d.id).distance(Math.max(40, pw / Math.sqrt(Math.max(N * 2, 4)))))
    .force('charge', d3.forceManyBody().strength(strength))
    .force('center', d3.forceCenter(W / 2, H / 2))
    .force('collide', d3.forceCollide(d => d.r + 10))
    .stop();
  for (let i = 0; i < 300; i++) sim.tick();

  // fit node centres to plot rect: non-uniform-safe affine, with room for radius and label
  const maxR = d3.max(nodes, n => n.r) || 0;
  const maxLw = d3.max(nodes, n => n.lw) || 0;
  const insetL = maxR + 4, insetR = maxR + 4 + maxLw, insetV = maxR + 8;
  const cx0 = d3.min(nodes, n => n.x), cx1 = d3.max(nodes, n => n.x);
  const cy0 = d3.min(nodes, n => n.y), cy1 = d3.max(nodes, n => n.y);
  const availW = Math.max(1, pw - insetL - insetR), availH = Math.max(1, ph - 2 * insetV);
  const sx = availW / Math.max(1, cx1 - cx0), sy = availH / Math.max(1, cy1 - cy0);
  nodes.forEach(n => {
    n.px = plotX0 + insetL + (cx1 - cx0 < 1 ? availW / 2 : (n.x - cx0) * sx);
    n.py = plotY0 + insetV + (cy1 - cy0 < 1 ? availH / 2 : (n.y - cy0) * sy);
  });

  const pathOf = d => {
    const a = d.source, b = d.target;
    if (a === b) {
      const r = a.r + 10;
      return `M${a.px},${a.py - a.r} C${a.px - r},${a.py - a.r - r * 2} ${a.px + r},${a.py - a.r - r * 2} ${a.px},${a.py - a.r}`;
    }
    const mx = (a.px + b.px) / 2, my = (a.py + b.py) / 2;
    const dx = b.px - a.px, dy = b.py - a.py;
    const cx = mx - dy * 0.18, cy = my + dx * 0.18;
    return `M${a.px},${a.py} Q${cx},${cy} ${b.px},${b.py}`;
  };

  const tip = options.allowTooltips !== false ? d3.llmTooltip(container) : null;
  const edgeLayer = svg.append('g');
  const nodeLayer = svg.append('g');

  const edges = edgeLayer.selectAll('path.d3-mark').data(links).join('path')
    .attr('class', 'd3-mark')
    .attr('data-row-idx', d => d.rows.join(','))
    .attr('d', pathOf)
    .attr('fill', 'none')
    .attr('stroke', d => colorOf(d.team))
    .attr('stroke-width', d => wScale(d.value))
    .attr('stroke-opacity', d => 0.35 + 0.5 * Math.sqrt(d.value / maxV))
    .attr('stroke-linecap', 'round')
    .style('cursor', 'pointer');
  if (tip) {
    edges.on('mousemove', (ev, d) => tip.show(`<b>${d.source.id} to ${d.target.id}</b><br/>Team: ${d.team}<br/>Sum of Orders: ${nf.format(d.value)}`, ev))
      .on('mouseleave', () => tip.hide());
  }

  const nodeG = nodeLayer.selectAll('g.node').data(nodes).join('g').attr('class', 'node');
  const circles = nodeG.append('circle')
    .attr('class', 'd3-mark')
    .attr('data-row-idx', d => d.rowIdx)
    .attr('cx', d => d.px).attr('cy', d => d.py).attr('r', d => d.r)
    .attr('fill', fg).attr('fill-opacity', 0.85)
    .attr('stroke', bg).attr('stroke-width', 1.5)
    .style('cursor', 'pointer');
  const labels = nodeG.append('text')
    .attr('class', 'd3-mark')
    .attr('data-row-idx', d => d.rowIdx)
    .attr('x', d => d.px + d.r + 4).attr('y', d => d.py)
    .attr('dy', '0.35em')
    .attr('font-size', 11).attr('fill', fg)
    .attr('stroke', bg).attr('stroke-width', 3).attr('stroke-opacity', 0.7)
    .style('paint-order', 'stroke').style('cursor', 'pointer')
    .text(d => d.id);
  if (tip) {
    [circles, labels].forEach(sel => sel
      .on('mousemove', (ev, d) => tip.show(`<b>${d.id}</b><br/>Total Orders (in and out): ${nf.format(d.tot)}`, ev))
      .on('mouseleave', () => tip.hide()));
  }

  // legend (Team)
  if (showLegend) {
    const lg = svg.append('g');
    const sw = 12;
    if (W >= 500) {
      lg.attr('transform', `translate(${W - legendW}, 14)`);
      lg.append('text').attr('x', 0).attr('y', 11).attr('font-size', 11).attr('font-weight', 600).attr('fill', fg).text('Team');
      let cy = 11 + 11 + 8;
      teams.forEach(t => {
        const e = lg.append('g');
        e.append('rect').attr('class', 'd3-legend-mark').attr('data-row-idx', teamRows.get(t).join(','))
          .attr('x', 0).attr('y', cy).attr('width', sw).attr('height', sw).attr('fill', colorOf(t)).style('cursor', 'pointer');
        e.append('text').attr('class', 'd3-legend-mark').attr('data-row-idx', teamRows.get(t).join(','))
          .attr('x', sw + 6).attr('y', cy + 10).attr('font-size', 11).attr('fill', fg).style('cursor', 'pointer').text(String(t));
        cy += 11 + 9;
      });
      cy += 6;
      const note = lg.append('text').attr('font-size', 10).attr('fill', fg).attr('x', 0).attr('y', cy + 10);
      ['Curves bend clockwise', 'from source to target.', 'Width: Sum of Orders.'].forEach((ln, i) => {
        note.append('tspan').attr('x', 0).attr('dy', i === 0 ? 0 : 13).text(ln);
      });
    } else {
      lg.attr('transform', 'translate(10, 6)');
      let x = 0, y = 0;
      lg.append('text').attr('x', 0).attr('y', 11).attr('font-size', 11).attr('font-weight', 600).attr('fill', fg).text('Team');
      x = 40;
      teams.forEach(t => {
        const w = sw + 6 + String(t).length * 6.5 + 12;
        if (x + w > W - 20) { x = 0; y += 16; }
        lg.append('rect').attr('class', 'd3-legend-mark').attr('data-row-idx', teamRows.get(t).join(','))
          .attr('x', x).attr('y', y + 1).attr('width', sw).attr('height', sw).attr('fill', colorOf(t)).style('cursor', 'pointer');
        lg.append('text').attr('class', 'd3-legend-mark').attr('data-row-idx', teamRows.get(t).join(','))
          .attr('x', x + sw + 6).attr('y', y + 11).attr('font-size', 11).attr('fill', fg).style('cursor', 'pointer').text(String(t));
        x += w;
      });
    }
  }

  // disclosure of unplaced rows
  if (skipped > 0) {
    svg.append('text').attr('x', 10).attr('y', H - 10).attr('font-size', 10).attr('fill', fg)
      .text(`${skipped} rows are not drawn: no positive value for Sum of Orders`);
  }
}

This chart was made by RegiaBI from the data above. Get it for Power BI or see pricing.

New articles in your inbox

Drop your email and we'll tell you when we publish something new. No spam — unsubscribe anytime.

This application may no longer respond until reloaded. Reload 🗙