HDI and GiniIndex by country

Where are HDI and GiniIndex both high, or both low?

Forty-five countries with seven indicators each: human development index, life expectancy, GDP per capita, mean years of schooling, internet users, CO2 per capita and a Gini index. The values are generated to look plausible and to move together; they are not official statistics, and a country's row should not be read as that country's real figures. Two numeric measures per country make it a sample for bivariate choropleths, scatter plots and correlation views.

Country Development Indicators (Illustrative): 45 rows, 8 columns. Download the CSV

The first 10 rows
CountryHDILifeExpectancyGDPPerCapitaEduYearsMeanInternetUsersPctCO2TonsPerCapitaGiniIndex
Norway0.67479.054758.011.271.45.2126.1
Switzerland0.62574.651040.012.058.25.6825.3
Ireland0.71579.050705.012.067.97.226.2
Germany0.71778.838873.011.280.56.0930.3
Australia0.86279.161214.013.289.88.1832.5
Iceland0.81584.550412.012.582.56.833.0
Sweden0.82978.353534.012.687.07.5230.3
Singapore0.9283.757018.013.990.28.0434.4
Netherlands0.9782.261552.015.598.28.2626.0
Denmark0.79882.055720.012.368.07.3136.4
A bivariate world choropleth of the "Country Development Indicators (Illustrative)" dataset: each country colored by HDI and GiniIndex.
A bivariate world choropleth of the "Country Development Indicators (Illustrative)" dataset: each country colored by HDI and GiniIndex.

How to read it

The color mixes two scales: read the key's grid to see where a country sits on each. Across 45 countries the two show a weak relationship (r = -0.18).

The chart's code (67 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
// English whatever the chart's language. A helper now asks for each one here and declares `// @requires llmText`:
d3.llmText = function (key, english, vars, count) {
var fill = function (s, vv) {
vv = vv || vars;
return String(s).replace(/\{([a-z][a-z0-9_]*)\}/g, function (m, k) {
return vv && Object.prototype.hasOwnProperty.call(vv, k) ? String(vv[k]) : m;
});
};
var en = fill(english);
var host = d3.llmText.host;
if (typeof host === 'function') {
try { var h = host(key, english, vars, count); if (typeof h === 'string' && h !== en && h !== english) return h; } catch (e) {}
}
var cat = d3.llmText._cat, lang = d3.llmText._lang;
if (cat && lang && Object.prototype.hasOwnProperty.call(cat, key)) {
var v = cat[key];
if (v && typeof v === 'object') {
var form = 'other';
try { form = new Intl.PluralRules(lang).select(typeof count === 'number' ? count : 0); } catch (e) {}
v = v[form] != null ? v[form] : v.other != null ? v.other : v.many;
}
var tv = vars;
if (vars && typeof vars.grain === 'string' && Object.prototype.hasOwnProperty.call(cat, 'd3.grain.' + vars.grain)
&& typeof cat['d3.grain.' + vars.grain] === 'string' && cat['d3.grain.' + vars.grain]) {
tv = {};
for (var vk in vars) if (Object.prototype.hasOwnProperty.call(vars, vk)) tv[vk] = vars[vk];
tv.grain = cat['d3.grain.' + vars.grain];
}
if (typeof v === 'string' && v) {
var t = fill(v, tv), left = String(t).match(/\{[a-z][a-z0-9_]*\}/g) || [];
if (left.every(function (x) { return en.indexOf(x) >= 0; })) return t;
}
}
return en;
};
d3.llmText._lang = null;
d3.llmText._cat = null;
d3.llmText.use = function (lang, catalog) {
d3.llmText._lang = lang || null; d3.llmText._cat = catalog || null;
d3.llmText.dates(lang);
};
d3.llmText.dates = function (lang) {
try {
var o = d3.llmText._d3orig;
if (!o) {
o = d3.llmText._d3orig = { timeFormat: d3.timeFormat, utcFormat: d3.utcFormat, timeParse: d3.timeParse,
utcParse: d3.utcParse, scaleTime: d3.scaleTime, scaleUtc: d3.scaleUtc };
}
var restore = function () { for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k) && o[k]) d3[k] = o[k]; };
var base = String(lang || '').toLowerCase().split(/[-_]/)[0];
if (!base || base === 'en' || typeof d3.timeFormatLocale !== 'function' || typeof Intl === 'undefined') { restore(); return; }
var mk = function (opts) { var x = { timeZone: 'UTC' }; for (var k in opts) x[k] = opts[k]; return new Intl.DateTimeFormat(lang, x); };
var months = [], shortMonths = [], days = [], shortDays = [], m, w;
var fM = mk({ month: 'long' }), fMs = mk({ month: 'short' }), fD = mk({ weekday: 'long' }), fDs = mk({ weekday: 'short' });
for (m = 0; m < 12; m++) { var dm = new Date(Date.UTC(2021, m, 15)); months.push(fM.format(dm)); shortMonths.push(fMs.format(dm)); }
for (w = 0; w < 7; w++) { var dw = new Date(Date.UTC(2021, 0, 3 + w)); days.push(fD.format(dw)); shortDays.push(fDs.format(dw)); }   // 3 Jan 2021 is a Sunday
if (months[0] === 'January' && days[0] === 'Sunday') { restore(); return; }   // no names for the language here: keep d3's
var L = d3.timeFormatLocale({ dateTime: '%x %X', date: '%Y-%m-%d', time: '%H:%M:%S', periods: ['AM', 'PM'],
days: days, shortDays: shortDays, months: months, shortMonths: shortMonths });
d3.timeFormat = L.format; d3.utcFormat = L.utcFormat; d3.timeParse = L.parse; d3.utcParse = L.utcParse;
var multi = function (utc) {
var F = utc ? L.utcFormat : L.format, P = utc ? 'utc' : 'time';
var iv = function (n) { return d3[P + n]; };
var fL = F('.%L'), fS = F(':%S'), fMi = F('%H:%M'), fH = F('%H:00'), fDy = F('%a %d'), fW = F('%b %d'), fMo = F('%B'), fY = F('%Y');
var wk = utc ? d3.utcSunday : d3.timeSunday;
return function (date) {
return (iv('Second')(date) < date ? fL : iv('Minute')(date) < date ? fS : iv('Hour')(date) < date ? fMi
: iv('Day')(date) < date ? fH : iv('Month')(date) < date ? (wk(date) < date ? fDy : fW)
: iv('Year')(date) < date ? fMo : fY)(date);
};
};
var wrap = function (make, utc) {
if (typeof make !== 'function') return make;
var dress = function (sc) {
var cp = sc.copy;
sc.tickFormat = function (count, spec) { return spec == null ? multi(utc) : (utc ? L.utcFormat : L.format)(spec); };
if (typeof cp === 'function') sc.copy = function () { return dress(cp.apply(sc, arguments)); };
return sc;
};
return function () { return dress(make.apply(this, arguments)); };
};
d3.scaleTime = wrap(o.scaleTime, false); d3.scaleUtc = wrap(o.scaleUtc, true);
} catch (e) {}
};
d3.llmFitLabel = function (sel, widthAccessor, opts) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: a string is fitted at no smaller size than a chart may draw it
if (widthAccessor != null && typeof widthAccessor === 'object' && !Array.isArray(widthAccessor)) {
var wobj = widthAccessor, wopts = {};
for (var wk in wobj) if (Object.prototype.hasOwnProperty.call(wobj, wk) && wk !== 'width' && wk !== 'room') wopts[wk] = wobj[wk];
if (opts != null && typeof opts === 'object') {
for (var wk2 in opts) if (Object.prototype.hasOwnProperty.call(opts, wk2)) wopts[wk2] = opts[wk2];
} else if (typeof opts === 'number' && opts > 0 && wopts.fontSize == null) {
wopts.fontSize = Math.max(TYPE_FLOOR, opts);
}
widthAccessor = wobj.width != null ? wobj.width : wobj.room;
opts = wopts;
}
if (typeof sel === 'string' || typeof sel === 'number') {
var so = (opts != null && typeof opts === 'object') ? opts
: ((arguments[3] != null && typeof arguments[3] === 'object') ? arguments[3] : {});
var sfs = Math.max(TYPE_FLOOR, (typeof opts === 'number' && opts > 0) ? opts : (+so.fontSize > 0 ? +so.fontSize : TYPE_FLOOR));
var sopts = {};
for (var sk in so) if (Object.prototype.hasOwnProperty.call(so, sk)) sopts[sk] = so[sk];
sopts.text = String(sel);
sopts.shrinkTo = null;
var holder = null, sn = null;
try {
if (typeof document !== 'undefined' && document && document.body && document.createElementNS) {
holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
holder.setAttribute('width', '0'); holder.setAttribute('height', '0');
holder.style.position = 'absolute'; holder.style.left = '-10000px'; holder.style.visibility = 'hidden';
sn = document.createElementNS('http://www.w3.org/2000/svg', 'text');
holder.appendChild(sn);
document.body.appendChild(holder);
}
} catch (e) { holder = null; sn = null; }
if (!sn) {
sn = { textContent: '', style: {}, fs: sfs,
getAttribute: function (a) { return a === 'font-size' ? String(sn.fs) : null; },
setAttribute: function (a, v) { if (a === 'font-size') sn.fs = +v; } };
}
var fitted;
try {
sn.setAttribute('font-size', String(sfs));
if (so.fontFamily) sn.setAttribute('font-family', String(so.fontFamily));
if (so.fontWeight) sn.setAttribute('font-weight', String(so.fontWeight));
d3.llmFitLabel({ each: function (fn) { fn.call(sn, null, 0); return this; } }, widthAccessor, sopts);
fitted = sn.textContent == null ? '' : String(sn.textContent);
} catch (e) { fitted = String(sel); }
try { if (holder && holder.parentNode) holder.parentNode.removeChild(holder); } catch (e) { /* detached */ }
return fitted;
}
opts = opts || {};
var pad = opts.pad == null ? 4 : opts.pad;
var minWidth = opts.minWidth == null ? 14 : opts.minWidth;
var ell = opts.ellipsis == null ? '\u2026' : opts.ellipsis;
var fallbackFs = opts.fontSize == null ? 10 : opts.fontSize;
var shrinkTo = opts.shrinkTo == null ? null : +opts.shrinkTo;
var overflow = opts.overflow === 'drop' ? 'drop' : 'truncate';
var sibs = Array.isArray(opts.distinctFrom) ? opts.distinctFrom : null;

if (!sel || typeof sel.each !== 'function') return sel;

var DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\uFF10-\uFF19]/;
var JOIN = /[.,'\u00A0\u202F\u2019\u066B\u066C]/;
var GLUED = /[A-Za-z%\u2030]/;
var LEAD = /[+\-\u2212$\u20AC\u00A3\u00A5\u20B9]/;
function numberSafeCut(s, lo) {
if (!(lo > 0) || lo >= s.length) return lo;
var a = s.charAt(lo - 1), b = s.charAt(lo);
var splits = DIGIT.test(a)
? (DIGIT.test(b) || GLUED.test(b) || (JOIN.test(b) && DIGIT.test(s.charAt(lo + 1))))
: (lo >= 2 && JOIN.test(a) && DIGIT.test(s.charAt(lo - 2)) && DIGIT.test(b));
if (!splits) return lo;
var i = lo;
while (i > 0 && (DIGIT.test(s.charAt(i - 1))
|| (i >= 2 && JOIN.test(s.charAt(i - 1)) && DIGIT.test(s.charAt(i - 2))))) i--;
while (i > 0 && LEAD.test(s.charAt(i - 1))) i--;
while (i > 0 && /\s/.test(s.charAt(i - 1))) i--;
return i;
}

function fontSizeOf(node) {
try {
var a = parseFloat(node.getAttribute && node.getAttribute('font-size'));
if (a > 0) return a;
var s = node.style && node.style.fontSize ? parseFloat(node.style.fontSize) : NaN;
if (s > 0) return s;
} catch (e) { /* fall through */ }
return fallbackFs;
}

function setFontSize(node, fs) {
try { if (node.setAttribute) node.setAttribute('font-size', String(fs)); } catch (e) { /* detached */ }
}

function measure(node, txt) {
try {
if (typeof node.getComputedTextLength === 'function') {
var w = node.getComputedTextLength();
if (w > 0) return w;
}
} catch (e) { /* fall through */ }
return String(txt).length * fontSizeOf(node) * 0.6;
}

function ownerSvg(node) {
try {
if (node.ownerSVGElement) return node.ownerSVGElement;
for (var p = node.parentNode; p; p = p.parentNode) {
if (p.nodeName && String(p.nodeName).toLowerCase() === 'svg') return p;
}
} catch (e) { /* detached */ }
return null;
}
function shownText(node) {
var kids = node && node.childNodes;
if (!kids || !kids.length) return node.textContent == null ? '' : String(node.textContent);
var s = '';
for (var c = 0; c < kids.length; c++) {
var k = kids[c];
if (k.nodeType === 3) s += k.nodeValue;
else if (k.nodeType === 1 && String(k.nodeName).toLowerCase() !== 'title') s += shownText(k);
}
return s;
}
function setShown(node, s) {
var kids = node.childNodes, keep = [];
if (kids && kids.length) {
for (var c = 0; c < kids.length; c++) {
if (kids[c].nodeType === 1 && String(kids[c].nodeName).toLowerCase() === 'title') keep.push(kids[c]);
}
}
node.textContent = s;
for (var q = 0; q < keep.length; q++) node.appendChild(keep[q]);
}
function hiddenIn(node, svg) {
try {
for (var p = node, hop = 0; p && hop < 64; p = p.parentNode, hop++) {
if (p.getAttribute && (p.getAttribute('display') === 'none' || p.getAttribute('visibility') === 'hidden')) return true;
if (p.style && (p.style.display === 'none' || p.style.visibility === 'hidden')) return true;
if (p === svg) break;
}
} catch (e) { /* read as shown */ }
return false;
}
function fittedFrom(node) {
return node.__llmFitFrom != null ? node.__llmFitFrom : node.__llmFullLabel;
}
function live(svg, en) {
if (shownText(en.node) !== en.visible) return false;
if (fittedFrom(en.node) != null && String(fittedFrom(en.node)) !== en.full) return false;
try { if (typeof svg.contains === 'function' && !svg.contains(en.node)) return false; } catch (e) { /* keep */ }
return true;
}
function endsWithText(s, t) { return s.length >= t.length && s.slice(s.length - t.length) === t; }
function ending(en, others) {
var f = en.full, n = en.node, E = en.ell;
if (en.drop) return '';
var fits = function (s) { setShown(n, s); return measure(n, s) <= en.room; };
var t = -1;
for (var s = f.length - 1; s >= 1 && t < 0; s--) {
var tl = f.slice(s), alone = true;
for (var o = 0; o < others.length && alone; o++) if (endsWithText(others[o], tl)) alone = false;
if (alone) t = s;
}
if (t < 1) return '';
if (DIGIT.test(f.charAt(t)) && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) {
while (t > 0 && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) t--;
}
if (t < 1) return '';
var ws = t;
while (ws > 0 && !/\s/.test(f.charAt(ws - 1))) ws--;
if (ws > 0 && ws < t && fits(E + f.slice(ws))) t = ws;
else if (!fits(E + f.slice(t))) return '';
var tail = f.slice(t), lo = 0, hi = t - 1;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
if (fits(f.slice(0, mid) + E + tail)) lo = mid; else hi = mid - 1;
}
var head = f.slice(0, numberSafeCut(f, lo)).replace(/\s+$/, '');
if (head.length < 2) head = '';
return head + E + tail;
}
function distinguish(group) {
var g, h, s, en, others;
for (g = 0; g < group.length; g++) {
en = group[g];
others = [];
for (h = 0; h < group.length; h++) if (group[h].full !== en.full) others.push(group[h].full);
try { s = ending(en, others); } catch (e) { s = ''; }
setShown(en.node, s);
en.visible = shownText(en.node);
}
for (g = 0; g < group.length; g++) {
for (h = g + 1; h < group.length; h++) {
var a = group[g], b = group[h];
if (a.visible && a.visible === b.visible && a.full !== b.full) {
setShown(a.node, ''); a.visible = '';
setShown(b.node, ''); b.visible = '';
}
}
}
}
function clashes(reg, svg, en) {
var group = [en], differ = false;
if (hiddenIn(en.node, svg)) return group;
for (var k = reg.length - 1; k >= 0; k--) {
var o = reg[k];
if (o === en || o.visible !== en.visible) continue;
if (!live(svg, o)) { reg.splice(k, 1); continue; }
if (hiddenIn(o.node, svg)) continue;
group.push(o);
if (o.full !== en.full) differ = true;
}
return differ ? group : [en];
}
function settle(node, room) {
var svg = ownerSvg(node);
if (!svg) return;
var reg = svg.__llmFitRegistry;
if (!Array.isArray(reg)) { reg = []; svg.__llmFitRegistry = reg; }
var k;
for (k = reg.length - 1; k >= 0; k--) if (reg[k].node === node) reg.splice(k, 1);
if (reg.length >= (reg.sweepAt || 256)) {
for (k = reg.length - 1; k >= 0; k--) if (!live(svg, reg[k])) reg.splice(k, 1);
reg.sweepAt = Math.max(256, reg.length * 2);
}
var vis = shownText(node);
if (!(room > 0) || !vis) return;
var me = { node: node, full: fittedFrom(node) == null ? vis : String(fittedFrom(node)),
visible: vis, room: room, ell: ell, drop: overflow === 'drop' };
reg.push(me);
var queue = [me];
for (var round = 0; queue.length && round < 32; round++) {
var en = queue.shift();
if (!en.visible) continue;
var group = clashes(reg, svg, en);
if (group.length < 2) continue;
distinguish(group);
for (var g = 0; g < group.length; g++) if (group[g].visible) queue.push(group[g]);
}
}

function fitOne(node, d, i) {
var full, alts = [];
if (opts.text != null) {
try {
full = typeof opts.text === 'function' ? opts.text.call(node, d, i) : opts.text;
} catch (e) { full = ''; }
if (Array.isArray(full)) { alts = full.slice(1); full = full[0]; }
full = full == null ? '' : String(full);
node.__llmFullLabel = full;
node.textContent = full;              // authoritative: an EMPTY label must CLEAR the node,
if (!full) return;                    // never leave the previous frame's text standing
} else {
full = node.__llmFullLabel;
if (full == null) {
full = node.textContent == null ? '' : String(node.textContent);
node.__llmFullLabel = full;
}
if (!full) return;
}
node.__llmFitFrom = null;
var fo = opts.forms;
if (typeof fo === 'function') { try { fo = fo.call(node, d, i); } catch (e) { fo = null; } }
if (fo != null) alts = alts.concat(Array.isArray(fo) ? fo : [fo]);
var cands = [full];
for (var ci = 0; ci < alts.length; ci++) {
var alt = alts[ci] == null ? '' : String(alts[ci]);
if (alt && cands.indexOf(alt) < 0) cands.push(alt);
}

var room;
try {
room = typeof widthAccessor === 'function'
? widthAccessor.call(node, d, i)
: widthAccessor;
} catch (e) { room = 0; }
room = (room == null ? 0 : +room) - pad * 2;

if (!(room > 0) || room < minWidth) { node.textContent = ''; return room; }

if (shrinkTo != null) {
if (node.__llmFullFontSize == null) node.__llmFullFontSize = fontSizeOf(node);
setFontSize(node, node.__llmFullFontSize);
}
node.textContent = full;
var w = measure(node, full);
if (w <= room) return room;                                // fits whole - done

var c;
for (c = 1; c < cands.length; c++) {
node.textContent = cands[c];
if (measure(node, cands[c]) <= room) { node.__llmFitFrom = cands[c]; return room; }
}

if (shrinkTo != null && shrinkTo > 0) {
for (c = 0; c < cands.length; c++) {
setFontSize(node, node.__llmFullFontSize);
node.textContent = cands[c];
var cur = fontSizeOf(node), wc = measure(node, cands[c]);
if (!(cur > shrinkTo)) break;
var fs = Math.max(shrinkTo, Math.floor((cur * room / wc) * 2) / 2);
for (; fs >= shrinkTo; fs -= 0.5) {
setFontSize(node, fs);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
setFontSize(node, shrinkTo);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
}
if (cands.length > 1) { full = cands[cands.length - 1]; node.__llmFitFrom = full; }
node.textContent = full;
if (overflow === 'drop') { node.textContent = ''; return room; }

var lo = 0, hi = full.length;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
node.textContent = full.slice(0, mid) + ell;
if (measure(node, node.textContent) <= room) lo = mid; else hi = mid - 1;
}
lo = numberSafeCut(full, lo);
if (sibs) {
var shared = 0;
for (var si = 0; si < sibs.length; si++) {
var o = sibs[si] == null ? '' : String(sibs[si]);
if (o === full) continue;
var k = 0;
while (k < o.length && k < full.length && o.charAt(k) === full.charAt(k)) k++;
if (k > shared) shared = k;
}
if (shared > 0 && lo <= shared) {
var a = 1, b = full.length;
while (a < b) {
var m = (a + b) >> 1;
node.textContent = ell + full.slice(m);
if (measure(node, node.textContent) <= room) b = m; else a = m + 1;
}
var inNum = function (i) {
return i > 0 && i < full.length && DIGIT.test(full.charAt(i))
&& (DIGIT.test(full.charAt(i - 1)) || (i >= 2 && JOIN.test(full.charAt(i - 1)) && DIGIT.test(full.charAt(i - 2))));
};
if (inNum(a)) {
var t0 = a;
while (t0 > 0 && (DIGIT.test(full.charAt(t0 - 1)) || (t0 >= 2 && JOIN.test(full.charAt(t0 - 1)) && DIGIT.test(full.charAt(t0 - 2))))) t0--;
node.textContent = ell + full.slice(t0);
a = measure(node, node.textContent) <= room ? t0 : full.length;
}
node.textContent = a < full.length ? ell + full.slice(a) : '';
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : '';
return room;
}

sel.each(function (d, i) {
var room = fitOne(this, d, i);
try { settle(this, room); } catch (e) { /* a failed sibling check leaves the fit as it stands */ }
});

return sel;
};
// @requires llmText
d3.llmGeoZoom = function (svg, opts) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: the hint and the pad glyphs draw no smaller
opts = opts || {};
if (!svg || typeof svg.append !== 'function') return null;
var still = function () {
return { layer: svg, still: true, group: function () { return svg.append('g'); },
reset: function () {}, step: function () {} };
};
if (typeof d3.zoom !== 'function' || typeof d3.zoomIdentity === 'undefined') return still();

var w = +opts.width, h = +opts.height;
var ox = +opts.originX || 0, oy = +opts.originY || 0;
if (!(w > 0) || !(h > 0)) return still();
var maxScale = +opts.maxScale > 1 ? +opts.maxScale : 8;
var fg = opts.themeFg || '#333';
var fs = Math.max(TYPE_FLOOR, +opts.fontSize > 0 ? +opts.fontSize : 11);
var coop = opts.cooperative === false ? false : true;
var onZoom = typeof opts.onZoom === 'function' ? opts.onZoom : null;
var hintText = opts.hintText || d3.llmText('d3.zoom.hint_pan', 'Use Ctrl (Cmd) + scroll to zoom, or drag to pan');

var clipId = 'llmzoomclip-' + Math.abs(((w * 131 + h * 17 + ox * 7 + oy) | 0));
svg.append('defs').append('clipPath').attr('id', clipId).append('rect')
.attr('x', ox).attr('y', oy).attr('width', w).attr('height', h);

var viewport = svg.append('g').attr('clip-path', 'url(#' + clipId + ')');
viewport.append('rect').attr('class', 'llm-zoom-surface')
.attr('x', ox).attr('y', oy).attr('width', w).attr('height', h)
.attr('fill', 'transparent');
var layer = viewport.append('g');

var groups = [];
function group(gopts) {
var g = layer.append('g');
groups.push({ g: g, o: gopts || {} });
return g;
}
function scaleGroups(k) {
if (!(k > 0)) return;
for (var gi = 0; gi < groups.length; gi++) {
var ge = groups[gi], go = ge.o;
try {
if (+go.stroke > 0) ge.g.selectAll('path:not([data-llm-edge])').attr('stroke-width', +go.stroke / k);
if (+go.dotStroke > 0) ge.g.selectAll('circle').each(dotScaler(+go.dotStroke, k));
} catch (e) { /* a border width is never worth breaking the chart for */ }
}
}
function dotScaler(dotStroke, k) {
return function () {
if (this.__llmBaseR == null) this.__llmBaseR = parseFloat(this.getAttribute('r'));
if (isFinite(this.__llmBaseR)) this.setAttribute('r', this.__llmBaseR / k);
this.setAttribute('stroke-width', dotStroke / k);
};
}

var ctrl = null;

var PAD_BTN = Math.max(15, Math.min(22, Math.round(fs * 1.7)));
var PAD_GAP = 2, PAD_W = PAD_BTN * 3 + PAD_GAP * 2;
var padX = ox + w - PAD_W - 6, padY = oy + 6;
var pad = null, panBtns = [];
if (w >= PAD_W + fs * 8 && h >= PAD_BTN * 3 + PAD_GAP * 2 + 16) {
pad = svg.append('g').attr('class', 'llm-zoom-pad');
var CELLS = [
[0, 0, 'in', '+'], [1, 0, 'up', '\u2191'], [2, 0, 'out', '\u2212'],
[0, 1, 'left', '\u2190'], [1, 1, 'reset', '\u27F2'], [2, 1, 'right', '\u2192'],
[1, 2, 'down', '\u2193']
];
for (var ci = 0; ci < CELLS.length; ci++) addPadButton(CELLS[ci]);
}
function addPadButton(cell) {
{
var bx = padX + cell[0] * (PAD_BTN + PAD_GAP);
var by = padY + cell[1] * (PAD_BTN + PAD_GAP);
var g = pad.append('g').attr('class', 'llm-zoom-btn lch-control').style('cursor', 'pointer')
.attr('aria-label', { 'in': d3.llmText('d3.zoom.in', 'Zoom in'), out: d3.llmText('d3.zoom.out', 'Zoom out'), reset: d3.llmText('d3.zoom.reset_view', 'Reset the view'), up: d3.llmText('d3.zoom.pan_up', 'Pan up'), down: d3.llmText('d3.zoom.pan_down', 'Pan down'), left: d3.llmText('d3.zoom.pan_left', 'Pan left'), right: d3.llmText('d3.zoom.pan_right', 'Pan right') }[cell[2]] || String(cell[2]));
g.append('rect').attr('x', bx).attr('y', by).attr('rx', 3)
.attr('width', PAD_BTN).attr('height', PAD_BTN)
.attr('fill', opts.backgroundColor || '#fff').attr('fill-opacity', 0.85)
.attr('stroke', fg).attr('stroke-opacity', 0.35);
g.append('text').attr('x', bx + PAD_BTN / 2).attr('y', by + PAD_BTN / 2)
.attr('text-anchor', 'middle').attr('dominant-baseline', 'central')
.attr('font-size', Math.max(TYPE_FLOOR, PAD_BTN - 6)).attr('fill', fg)
.style('pointer-events', 'none').text(cell[3]);
g.on('click', function (event) {
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
llmZoomStep(cell[2]);
});
if (cell[2] === 'reset') { ctrl = g; g.style('opacity', 0.35); panBtns.push(g); }
else if (cell[2] !== 'in' && cell[2] !== 'out') { g.style('opacity', 0.35); panBtns.push(g); }
}
}

var hint = svg.append('g').style('display', 'none').style('pointer-events', 'none');
hint.append('rect').attr('x', ox + w / 2 - fs * 12).attr('y', oy + h / 2 - fs).attr('rx', 4)
.attr('width', fs * 24).attr('height', fs * 2)
.attr('fill', fg).attr('fill-opacity', 0.72);
hint.append('text').attr('x', ox + w / 2).attr('y', oy + h / 2 + fs * 0.4)
.attr('text-anchor', 'middle').attr('font-size', fs)
.attr('fill', opts.backgroundColor || '#fff').text(hintText);

var hintFitted = false;
function fitHint(cx, cy, frameW, f) {
var t = hint.select('text'), r = hint.select('rect'), words = String(t.text() || '');
function tw(s) { t.text(s); var v = 0; try { v = t.node().getComputedTextLength(); } catch (eM) { v = 0; } return v > 0 ? v : s.length * f * 0.6; }
var maxW = Math.max(f * 6, frameW - f * 3), parts = /\s/.test(words.trim()) ? words.trim().split(/\s+/) : Array.from(words), sep = /\s/.test(words.trim()) ? ' ' : '';
var lines = [], cur = '';
parts.forEach(function (wd) {
var nx = cur ? cur + sep + wd : wd;
if (cur && tw(nx) > maxW) { lines.push(cur); cur = wd; } else cur = nx;
});
if (cur) lines.push(cur);
var widest = 0;
lines.forEach(function (ln) { widest = Math.max(widest, tw(ln)); });
var lh = f * 1.25, boxW = Math.min(frameW - f, widest + f * 1.6), boxH = lines.length * lh + f * 0.75;
t.text(null);
lines.forEach(function (ln, i) {
t.append('tspan').attr('x', cx).attr('y', cy - (lines.length - 1) * lh / 2 + i * lh + f * 0.4).text(ln);
});
r.attr('x', cx - boxW / 2).attr('y', cy - boxH / 2).attr('width', boxW).attr('height', boxH);
}
var hintTimer = null;
function showHint() {
try {
hint.raise().style('display', null).style('opacity', 1);
if (!hintFitted) { hintFitted = true; fitHint(ox + w / 2, oy + h / 2, w, fs); }
if (hintTimer) clearTimeout(hintTimer);
hintTimer = setTimeout(function () { hint.style('display', 'none'); }, 1500);
} catch (e) { /* a hint is never worth breaking the chart for */ }
}

function filt(event) {
if (!event) return false;
if (event.type === 'wheel') {
if (!coop || event.ctrlKey || event.metaKey) return true;
showHint();
return false;
}
if (event.touches) {
if (!coop) return true;
if (event.touches.length < 2) { showHint(); return false; }
return true;
}
if (event.type === 'dblclick') return true;
return !event.button;                       // primary-button drag pans
}

var adopted = false, adoptedBaseR = null;
function adopt() {
if (adopted) return;
adopted = true;
try {
var layerNode = layer.node(), svgNode = svg.node();
if (!layerNode || !svgNode) return;
if (layerNode.childNodes.length) return;          // drawn correctly - nothing to do
var kids = [].slice.call(svgNode.childNodes), moved = 0;
for (var i = 0; i < kids.length; i++) {
var n = kids[i];
if (n.nodeType !== 1 || !n.querySelector) continue;
if (n === viewport.node() || n === hint.node()) continue;
if (ctrl && n === ctrl.node()) continue;
if (pad && n === pad.node()) continue;
if (n.tagName === 'defs' || n.tagName === 'title') continue;
var isFurniture = (n.classList && n.classList.contains('d3-legend-mark'))
|| n.querySelector('.d3-legend-mark');
if (isFurniture) continue;
var holdsMap = n.tagName === 'path'
|| (n.classList && n.classList.contains('d3-mark'))
|| n.querySelector('.d3-mark')
|| (n.tagName === 'g' && n.querySelector('path'));
if (!holdsMap) continue;
layerNode.appendChild(n);                        // document order is preserved
moved++;
}
if (!moved) return;
adoptedBaseR = [];
var ms = layerNode.querySelectorAll('.d3-mark');
for (var j = 0; j < ms.length; j++) {
var r = parseFloat(ms[j].getAttribute('r'));
if (isFinite(r)) adoptedBaseR.push([ms[j], r, parseFloat(ms[j].getAttribute('stroke-width')) || 0]);
}
} catch (e) { /* a heal is never worth breaking the chart for */ }
}

var textBase = null;
function scaleLayerText(k) {
if (!(k > 0)) return;
try {
var layerNode = layer.node();
if (!layerNode) return;
var ts = layerNode.querySelectorAll('text');
if (textBase === null || textBase.length !== ts.length) {
textBase = [];
for (var i = 0; i < ts.length; i++) {
var cs = null;
try { cs = window.getComputedStyle(ts[i]).fontSize; } catch (e) { cs = null; }
var px = parseFloat(ts[i].getAttribute('font-size'));
if (!isFinite(px)) px = parseFloat(cs);
textBase.push(isFinite(px) && px > 0 ? px : 0);
}
}
for (var j = 0; j < ts.length; j++) {
if (textBase[j] > 0) ts[j].setAttribute('font-size', (textBase[j] / k).toFixed(2));
}
} catch (e) { /* a label size is never worth breaking the chart for */ }
}

function scaleAdopted(k) {
if (!adoptedBaseR || !(k > 0)) return;
for (var i = 0; i < adoptedBaseR.length; i++) {
var e = adoptedBaseR[i];
e[0].setAttribute('r', e[1] / k);
if (e[2]) e[0].setAttribute('stroke-width', e[2] / k);
}
}

var zoom = d3.zoom()
.wheelDelta(function (event) {
return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002);
})
.scaleExtent([1, maxScale])
.extent([[0, 0], [w, h]])
.translateExtent([[0, 0], [w, h]])
.clickDistance(4)
.filter(filt)
.on('zoom', function (event) {
var t = event && event.transform ? event.transform : d3.zoomIdentity;
adopt();                       // no-op when the chart drew into the layer as intended
layer.attr('transform', t.toString());
scaleAdopted(t.k);
scaleLayerText(t.k);
scaleGroups(t.k);
if (onZoom) { try { onZoom(t); } catch (e) { /* never break the render */ } }
try {
if (ctrl) ctrl.style('opacity', t.k > 1.001 ? 1 : 0.35);
for (var pi = 0; pi < panBtns.length; pi++) panBtns[pi].style('opacity', t.k > 1.001 ? 1 : 0.35);
if (pad) pad.raise();
} catch (e) { /* ignore */ }
});

try { viewport.call(zoom); } catch (e) { if (pad) pad.remove(); return { layer: layer, group: group, reset: function () {}, step: function () {} }; }

function reset() {
try { viewport.call(zoom.transform, d3.zoomIdentity); } catch (e) { /* ignore */ }
}

function llmZoomStep(dir) {
try {
if (dir === 'reset') { reset(); return; }
if (dir === 'in') { viewport.call(zoom.scaleBy, 1.6); return; }
if (dir === 'out') { viewport.call(zoom.scaleBy, 1 / 1.6); return; }
var t = d3.zoomTransform(viewport.node());
var k = t && t.k > 0 ? t.k : 1;
var dx = (w * 0.18) / k, dy = (h * 0.18) / k;
if (dir === 'left') viewport.call(zoom.translateBy, dx, 0);
else if (dir === 'right') viewport.call(zoom.translateBy, -dx, 0);
else if (dir === 'up') viewport.call(zoom.translateBy, 0, dy);
else if (dir === 'down') viewport.call(zoom.translateBy, 0, -dy);
} catch (e) { /* a control is never worth breaking the chart for */ }
}

return { layer: layer, group: group, reset: reset, zoom: zoom, viewport: viewport, pad: pad, step: llmZoomStep };
};
d3.llmPlaceUnit = function (data) {
var WORDS = { country: ['country', 'countries'], state: ['state', 'states'], area: ['area', 'areas'], region: ['region', 'regions'] };
var votes = { country: 0, state: 0, area: 0, region: 0 };
try {
var cols = data && data.columns ? data.columns : [];
var at = -1;
for (var c = 0; c < cols.length; c++) if (cols[c] && cols[c].name === '__geoIso__') { at = c; break; }
var rows = at >= 0 && data.rows ? data.rows : [];
for (var r = 0; r < rows.length; r++) {
var v = rows[r] ? rows[r][at] : null;
if (v === null || v === undefined || v === '') continue;
var s = String(v).trim();
if (/^[A-Z]{3}$/.test(s)) votes.country++;
else if (/^[A-Z]{2}$/.test(s)) votes.state++;
else if (/^[0-9]{3,5}$/.test(s)) votes.area++;
else votes.region++;
}
} catch (e) { /* an unreadable table counts nothing: the word below is 'region' */ }
var best = 'region', most = 0;
['country', 'state', 'area', 'region'].forEach(function (k) { if (votes[k] > most) { most = votes[k]; best = k; } });
var w = WORDS[best];
return {
one: w[0],
many: w[1],
count: function (n) { return n + ' ' + (+n === 1 ? w[0] : w[1]); }
};
};
d3.llmWorldFit = function (proj, opts) {
opts = opts || {};
var FAR_SOUTH = -60;
var geo = (opts.geo && opts.geo.features && opts.geo.features.length) ? opts.geo : null;
var mapW = +opts.width || 0, mapH = +opts.height || 0;
var pad = isFinite(+opts.pad) && opts.pad !== null && opts.pad !== undefined ? +opts.pad : 8;
var vp = opts.viewport || [mapW, mapH];
var VW = +vp[0] || mapW, VH = +vp[1] || mapH;
var pts = (opts.points || []).filter(function (p) {
return p && p.length > 1 && p[0] !== null && p[1] !== null && isFinite(+p[0]) && isFinite(+p[1]);
});

var isFarSouth = function (f) { var b = d3.geoBounds(f); return b[1][1] < FAR_SOUTH; };
var anyFarSouth = pts.some(function (p) { return +p[1] < FAR_SOUTH; })
|| (opts.regions || []).some(function (f) { return !!f && isFarSouth(f); });
var trimSouth = !!geo && !anyFarSouth;
var sliver = trimSouth ? Math.max(8, Math.round(Math.min(VW, VH) * 0.03)) : 0;

var box = opts.box || [[pad, pad], [mapW - pad, mapH - pad]];
var x0 = box[0][0], y0 = box[0][1], x1 = box[1][0], y1 = box[1][1];
var polys = geo ? geo.features.filter(function (f) { return f.geometry && f.geometry.type !== 'Point'; }) : [];
var fitGeo = (geo && opts.fitPolygons && polys.length) ? { type: 'FeatureCollection', features: polys } : geo;
var fitTo = function (bottom) {
if (geo) proj.fitExtent([[x0, y0], [x1, bottom]], fitGeo);
else if (pts.length) proj.fitExtent(opts.pointBox || [[x0, y0], [x1, bottom]], { type: 'MultiPoint', coordinates: pts });
};
fitTo(y1);
var path = d3.geoPath(proj);

var farSouthCol = { type: 'FeatureCollection', features: polys.filter(isFarSouth) };
if (opts.refit !== false && trimSouth && farSouthCol.features.length) {
var fsB = path.bounds(farSouthCol), worldB = path.bounds(geo);
var cut = fsB[0][1] + sliver;                  // where the clip will land
var crop = Math.max(0, worldB[1][1] - cut);    // dead space this would leave
if (crop > 1) { fitTo(y1 + crop); path = d3.geoPath(proj); }
}
var aTop = opts.anchorLow;
if (trimSouth && aTop !== undefined && aTop !== null && isFinite(+aTop)) {
var vis = polys.filter(function (f) { return !isFarSouth(f); });
if (vis.length) {
var vb = path.bounds({ type: 'FeatureCollection', features: vis });
var cutA = farSouthCol.features.length ? path.bounds(farSouthCol)[0][1] + sliver : vb[1][1];
var slackTop = Math.max(0, vb[0][1] - aTop);
var slackBottom = Math.max(0, y1 - cutA);
var bottomGap = Math.max(24, Math.round((slackTop + slackBottom) * 0.3));
var dy = Math.round((mapH - bottomGap) - cutA);
if (dy > 1) {
var t = proj.translate();
proj.translate([t[0], t[1] + Math.min(dy, slackTop + slackBottom)]);
path = d3.geoPath(proj);
}
}
}
var farSouthTop = farSouthCol.features.length ? path.bounds(farSouthCol)[0][1] : Infinity;
var clipBottom = (trimSouth && isFinite(farSouthTop)) ? Math.min(mapH, farSouthTop + sliver) : mapH;
var clipTop = +opts.clipTop || 0;

var clipId = 'llmgeoclip-' + Math.abs((VW * 131 + VH) | 0);
var defineClip = function (svg) {
svg.append('defs').append('clipPath').attr('id', clipId).append('rect')
.attr('x', 0).attr('y', clipTop).attr('width', mapW).attr('height', Math.max(1, clipBottom - clipTop));
};
var basemap = function (svg, layer, plain) {
if (!geo || !svg || !layer) return null;
defineClip(svg);
var g = layer.append('g');
if (plain) return g.attr('clip-path', 'url(#' + clipId + ')');
return g.attr('class', 'llm-basemap').attr('clip-path', 'url(#' + clipId + ')')
.style('pointer-events', 'none');
};
var clip = function (svg, g) {
if (!geo || !svg || !g) return g;
defineClip(svg);
return g.attr('clip-path', 'url(#' + clipId + ')');
};

return { path: path, projection: proj, trimSouth: trimSouth, clipBottom: clipBottom, clipTop: clipTop,
sliver: sliver, farSouth: FAR_SOUTH, basemap: basemap, clip: clip };
};
// @requires llmFilterScope
d3.llmBivariate = function (cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: the arm labels draw no smaller, and the size promised is at that size
cfg = cfg || {};
var num = function (v) { return (v == null || v === '' || !isFinite(+v)) ? null : +v; };
var xin = cfg.x || [], yin = cfg.y || [];
var n = Math.min(xin.length, yin.length);
var xs = [], ys = [];
for (var i = 0; i < n; i++) {
var a = num(xin[i]), b = num(yin[i]);
if (a != null && b != null) { xs.push(a); ys.push(b); }   // PAIRED regions only
}
var xLabel = cfg.xLabel || 'x', yLabel = cfg.yLabel || 'y';

var GROWTH_RE = /\b(growth|yoy|mom|qoq|wow|change|gap|variance|delta)\b/i;
var PLAN_RE = /\b(attainment|achievement|of (target|plan|quota|budget)|vs\.? (target|plan|quota|budget)|to (target|plan|quota))\b/i;
var words = function (s) {
return String(s == null ? '' : s).replace(/YoY|MoM|QoQ|WoW/g, function (m) { return ' ' + m.toLowerCase() + ' '; })
.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ');
};
var median = function (vals) { var a = vals.slice().sort(function (p, q) { return p - q; }); var m = a.length >> 1; return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2; };
var refOf = function (given, label, vals) {
if (given === null) return null;
if (given !== undefined) { var g = num(given); return g == null ? null : g; }
if (!vals.length) return null;
var w = words(label);
if (PLAN_RE.test(w)) {
var md = median(vals), best = 0;
[0, 1, 100].forEach(function (c) { if (Math.abs(md - c) < Math.abs(md - best)) best = c; });
return best;
}
return GROWTH_RE.test(w) ? 0 : null;
};
var mk = function (vals, ref) {
if (!vals.length) return { bin: function () { return null; }, thresholds: [], flat: true, ref: null, band: 0 };
var lo = Math.min.apply(null, vals), hi = Math.max.apply(null, vals);
if (ref != null) {
var band = 0.025 * (hi - lo);
return { bin: function (v) { return v < ref - band ? 0 : (v > ref + band ? 2 : 1); }, thresholds: [ref - band, ref + band], flat: false, ref: ref, band: band };
}
if (lo === hi) return { bin: function () { return 1; }, thresholds: [], flat: true, ref: null, band: 0 };
var q = d3.scaleQuantile().domain(vals).range([0, 1, 2]);
return { bin: function (v) { return q(v); }, thresholds: q.quantiles(), flat: false, ref: null, band: 0 };
};
var fopts = cfg.options || (cfg.canvas && typeof cfg.canvas === 'object' ? cfg.canvas : null);
if (fopts) {
var fscope = d3.llmFilterScope(fopts);
var kx = fscope.domain('llmBivariate:x', xs), ky = fscope.domain('llmBivariate:y', ys);
if (fscope.narrowed && kx.cohort === 'all' && ky.cohort === 'all') { xs = kx.values; ys = ky.values; }
}
var QX = mk(xs, refOf(cfg.xRef, xLabel, xs)), QY = mk(ys, refOf(cfg.yRef, yLabel, ys));
var xBin = function (v) { v = num(v); return v == null ? null : QX.bin(v); };
var yBin = function (v) { v = num(v); return v == null ? null : QY.bin(v); };

var STEVENS = ['#e5e4b9', '#ace4e4', '#5ac8c8', '#dfb0d6', '#a5add3', '#5698b9', '#be64ac', '#8c62aa', '#3b4994'];
var LOW_LOW_ON_DARK = '#f8f8d8';
var forced = !!(cfg.colorScaleLow || cfg.colorScaleHigh);
var colors;
if (!forced) {
colors = STEVENS.slice();
} else {
var lo2 = cfg.colorScaleLow || '#eef3f8';
var hi2 = cfg.colorScaleHigh || cfg.palettePrimary || '#3182bd';
var ramp = (typeof d3.interpolateLab === 'function') ? d3.interpolateLab(lo2, hi2) : d3.interpolateRgb(lo2, hi2);
colors = [];
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 3; k++) {
var base = d3.color(ramp(k / 2)) || d3.color(hi2);
var c = j === 0 ? base.brighter(0.9) : (j === 1 ? base : base.darker(0.9));
colors.push(c.formatHex());
}
}
}
var cv = cfg.canvas, cvHc = !!cfg.highContrast;
if (cv && typeof cv === 'object') {
cvHc = !!cv.isHighContrast;
cv = cv.backgroundColor && cv.backgroundColor !== 'transparent' ? cv.backgroundColor : cv.themeBg;
}
var cvColor = cv ? d3.color(cv) : null;
var lumOf = function (c) {
var q = d3.rgb(c);
var f = function (u) { u /= 255; return u <= 0.03928 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4); };
return 0.2126 * f(q.r) + 0.7152 * f(q.g) + 0.0722 * f(q.b);
};
var onPage = function (c) { var a = lumOf(c), b = lumOf(cvColor); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); };
var darkCanvas = !!(cvColor && !cvHc && cvColor.opacity >= 1 && lumOf(cvColor) < 0.2);
var offPage = function (c, floor) {
var q = d3.lab(c);
if (!isFinite(q.l)) return c;
for (var i = 0; i < 60 && q.l < 100 && onPage(q.formatHex()) < floor; i++) q.l = Math.min(100, q.l + 2);
return q.formatHex();
};
if (darkCanvas && !forced) colors[0] = LOW_LOW_ON_DARK;
if (darkCanvas) colors = colors.map(function (c) { return offPage(c, 3); });
var EDGE_W = 1;
var pageC = cvColor && cvColor.opacity >= 1 ? cvColor : d3.color('#ffffff');
var onCard = function (c) { var a = lumOf(c), b = lumOf(pageC); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); };
var edge = null;
if (onCard(colors[0]) < 1.5) {
var eq = d3.lab(colors[0]);
for (var ei = 0; ei < 100 && eq.l > 0 && onCard(eq.formatHex()) < 3; ei++) eq.l = Math.max(0, eq.l - 1);
edge = { stroke: eq.formatHex(), width: EDGE_W };
}
var edgeFor = function (xv, yv) { return edge && xBin(xv) === 0 && yBin(yv) === 0 ? edge : null; };
var colorFor = function (xv, yv) {
var a = xBin(xv), b = yBin(yv);
return (a == null || b == null) ? null : colors[b * 3 + a];
};
var pxlo = xs.length ? Math.min.apply(null, xs) : 0, pxhi = xs.length ? Math.max.apply(null, xs) : 1;
var pRamp = (typeof d3.interpolateLab === 'function') ? d3.interpolateLab(colors[0], colors[2]) : d3.interpolateRgb(colors[0], colors[2]);
var primaryColor = function (xv) {
xv = num(xv); if (xv == null) return null;
var t = pxhi === pxlo ? 0.5 : (xv - pxlo) / (pxhi - pxlo);
return d3.color(pRamp(Math.max(0, Math.min(1, t)))).formatHex();
};

var occupancy = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for (var r = 0; r < xs.length; r++) occupancy[QY.bin(ys[r]) * 3 + QX.bin(xs[r])]++;
var emptyCells = occupancy.filter(function (c) { return c === 0; }).length;
var NAMES = ['low', 'mid', 'high'], REF_NAMES = ['below', 'near', 'above'];
var thirdName = function (bin, axis) {
if (bin == null) return 'no data';
var Q = axis === 'x' ? QX : axis === 'y' ? QY : null;
var byRef = Q ? Q.ref != null : (QX.ref != null && QY.ref != null);
return (byRef ? REF_NAMES : NAMES)[bin];
};

var shortLabel = function (s) {
var t = String(s == null ? '' : s);
var m = t.replace(/^(sum|average|avg|count|distinct count|min|minimum|max|maximum|median|standard deviation|variance|first|last) of\s+/i, '');
return m.length ? m : t;
};
var xArm = shortLabel(xLabel), yArm = shortLabel(yLabel);
var textRun = function (s, fs) { return String(s == null ? '' : s).length * fs * 0.58; };

var forcedNote = forced
? ('Color Scale (Low/High) applied to ' + xLabel + '; ' + yLabel + ' runs light to dark')
: null;
var refText = function (r) { return r === 1 ? '100%' : String(r); };
var captionText = QX.ref == null && QY.ref == null
? xLabel + ' (→) by ' + yLabel + ' (↑), each split into thirds: low / mid / high'
: QX.ref != null && QY.ref != null
? xLabel + ' (→) split at ' + refText(QX.ref) + ' by ' + yLabel + ' (↑) split at ' + refText(QY.ref) + ': below / near / above'
: (QX.ref != null
? xLabel + ' (→) split at ' + refText(QX.ref) + ': below / near / above; ' + yLabel + ' (↑) in thirds: low / mid / high'
: xLabel + ' (→) in thirds: low / mid / high; ' + yLabel + ' (↑) split at ' + refText(QY.ref) + ': below / near / above');

var ARM_CHARS = 18;
var armCap = function (cell, fs) { return Math.max(6 * cell, ARM_CHARS * fs * 0.58); };
var armFull = function (name, isY) { return isY ? '← ' + name : name + ' →'; };
var armText = function (name, isY, cell, fs) {
var full = armFull(name, isY), cap = armCap(cell, fs);
if (textRun(full, fs) <= cap) return full;
var keep = Math.max(1, Math.floor(cap / (fs * 0.58) + 1e-9) - 3);   // the arrow, its space, the ellipsis
var s = String(name), cut = s.slice(0, keep), sp = cut.lastIndexOf(' ');
if (s.charAt(keep) !== ' ' && sp >= Math.ceil(keep / 2)) cut = cut.slice(0, sp);
return armFull(cut.replace(/\s+$/, '') + '…', isY);
};
var armRun = function (name, isY, cell, fs) {
return Math.min(textRun(armFull(name, isY), fs), armCap(cell, fs));
};
var geom = function (cell, fontSize) {
fontSize = Math.max(TYPE_FLOOR, +fontSize || 0);
var D = 3 * cell * Math.SQRT2, K = Math.SQRT1_2, e = 1.5 * cell, h = D / 2;
var yy = e + 4 + fontSize, xx = e + 6 + fontSize;   // each label's baseline, out from the centre
var ax = -e + 2, by = e - 2;                        // where each label meets the corner
var Lx = armRun(xArm, false, cell, fontSize), Ly = armRun(yArm, true, cell, fontSize);
var hL = Math.max(h, K * (xx - by + Ly), -K * (ax + yy));
var hR = Math.max(h, K * (ax + Lx + yy), K * (by - xx));
var hT = Math.max(h, -K * (yy - ax - Lx), -K * (by - Ly + xx));
var hB = Math.max(h, K * (yy - ax), K * (by + xx));
return { width: Math.round(hL + hR + 8), height: Math.round(hT + hB + 6),
cx: hL + 4, cy: hT + 3, D: D, e: e };
};
var legendSize = function (cell, fontSize) {
var g = geom(cell, fontSize);
return { width: g.width, height: g.height };
};
var drawLegend = function (svg, o) {
o = o || {};
var cell = o.cell || 12, fs = Math.max(TYPE_FLOOR, o.fontSize || TYPE_FLOOR), fg = o.themeFg || '#333';
var gm = geom(cell, fs), size = { width: gm.width, height: gm.height };
var g = svg.append('g').attr('class', 'llm-bivariate-legend')
.attr('transform', 'translate(' + (o.x || 0) + ',' + (o.y || 0) + ')')
.attr('data-w', size.width).attr('data-h', size.height);
var D = gm.D;
var cx = gm.cx, cy = gm.cy;   // the box leans with the labels; the grid is NOT at its centre
var rot = g.append('g').attr('transform', 'translate(' + cx + ',' + cy + ') rotate(-45)');
for (var jj = 0; jj < 3; jj++) {
for (var ii = 0; ii < 3; ii++) {
rot.append('rect').attr('class', 'llm-bivariate-cell')
.attr('x', (ii - 1.5) * cell).attr('y', (0.5 - jj) * cell)
.attr('width', cell).attr('height', cell)
.attr('fill', colors[jj * 3 + ii])
.attr('stroke', edge && jj === 0 && ii === 0 ? edge.stroke : '#fff').attr('stroke-width', edge && jj === 0 && ii === 0 ? edge.width : 0.5);
}
}
var e = 1.5 * cell;
rot.append('line').attr('x1', -e).attr('y1', e + 3).attr('x2', e).attr('y2', e + 3)
.attr('stroke', fg).attr('stroke-width', 0.8).attr('opacity', 0.7);
rot.append('line').attr('x1', -e - 3).attr('y1', e).attr('x2', -e - 3).attr('y2', -e)
.attr('stroke', fg).attr('stroke-width', 0.8).attr('opacity', 0.7);
rot.append('text').attr('class', 'llm-bivariate-x').attr('x', -e + 2).attr('y', e + 4 + fs)
.attr('text-anchor', 'start').attr('font-size', fs).attr('fill', fg)
.text(armText(xArm, false, cell, fs));
rot.append('text').attr('class', 'llm-bivariate-y')
.attr('transform', 'translate(' + (-e - 6 - fs) + ',' + (e - 2) + ') rotate(90)')
.attr('text-anchor', 'end').attr('font-size', fs).attr('fill', fg)
.text(armText(yArm, true, cell, fs));
return { width: size.width, height: size.height };
};
return {
xBin: xBin, yBin: yBin, colors: colors, colorFor: colorFor, primaryColor: primaryColor,
thirdName: thirdName, occupancy: occupancy, emptyCells: emptyCells,
thresholds: { x: QX.thresholds, y: QY.thresholds }, paired: xs.length,
references: { x: QX.ref, y: QY.ref }, nearBand: { x: QX.band, y: QY.band },
forced: forced, forcedNote: forcedNote, captionText: captionText,
legendSize: legendSize, drawLegend: drawLegend, edge: edge, edgeFor: edgeFor,
landFill: function (c) {
if (!darkCanvas) return c || '#cfcfcf';
return offPage(c || d3.lab(d3.lab(cvColor).l, 0, 0).formatHex(), 3);
},
};
};
d3.llmLegendLayout = function (o) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: a caption line draws no smaller
o = o || {};
var W = +o.width > 0 ? +o.width : 0, H = +o.height > 0 ? +o.height : 0;
var lg = o.legend || {};
var lw = Math.max(0, +lg.width || 0), lh = Math.max(0, +lg.height || 0);
var band = Math.max(0, +o.band || 0);
var edge = o.edge === 'bottom' ? 'bottom' : 'top';
var side = o.side === 'right' ? 'right' : 'left';
var top = Math.max(0, +o.top || 0);
var bottom = o.bottom == null ? 14 : Math.max(0, +o.bottom || 0);
var pad = o.pad == null ? 6 : Math.max(0, +o.pad || 0);
var inset = o.inset == null ? 8 : Math.max(0, +o.inset || 0);
var minGain = +o.minGain > 1 ? +o.minGain : 1.05;
var maxCol = +o.maxColumn > 0 ? +o.maxColumn : 0.34;   // a column wider than this share of W is never offered
var LINE_GAP = 4, WRAP_GAP = 2, ITEM_GAP = 8;
var items = (o.items || []).filter(function (it) { return it && it.text != null && String(it.text) !== ''; });
var fsOf = function (it) { return Math.max(TYPE_FLOOR, +it.fontSize > 0 ? +it.fontSize : TYPE_FLOOR); };
var run = function (s, fs) { return String(s).length * fs * 0.6; };
var swatchRoom = function (it, fs) { return it.swatch ? Math.round(fs * 0.8) + 4 : 0; };
var wrap = function (text, width, fs) {
var words = String(text).split(/\s+/), lines = [], cur = '';
for (var i = 0; i < words.length; i++) {
if (!words[i]) continue;
var t = cur ? cur + ' ' + words[i] : words[i];
if (cur && run(t, fs) > width) { lines.push(cur); cur = words[i]; } else cur = t;
}
if (cur) lines.push(cur);
return lines.length ? lines : [''];
};

var proj = o.projection, obj = o.object;
var measure = typeof o.fit === 'function' ? o.fit
: (proj && obj && typeof proj.fitExtent === 'function')
? function (box) { proj.fitExtent(box, obj); return proj.scale(); } : null;
var scaleOf = function (box) {
if (!measure || !(box[1][0] - box[0][0] > 1) || !(box[1][1] - box[0][1] > 1)) return null;
var s = +measure(box);
return isFinite(s) && s > 0 ? s : null;
};

var bandBox = edge === 'top'
? [[pad, top + band], [W - pad, H - bottom]]
: [[pad, top + pad], [W - pad, H - band]];
var colW = Math.ceil(lw + 2 * inset);
var sideBox = side === 'left'
? [[colW, top + pad], [W - pad, H - bottom]]
: [[pad, top + pad], [W - colW, H - bottom]];
var sideItems = [], itemsH = 0;
for (var si = 0; si < items.length; si++) {
var sfs = fsOf(items[si]);
var sl = wrap(items[si].text, Math.max(1, lw - swatchRoom(items[si], sfs)), sfs);
sideItems.push({ it: items[si], fs: sfs, lines: sl });
itemsH += (si ? LINE_GAP : 0) + sl.length * sfs + (sl.length - 1) * WRAP_GAP;
}
var colNeed = inset + lh + (sideItems.length ? ITEM_GAP + itemsH : 0);
var sideOk = W > 0 && H > 0 && lw > 0 && colW <= W * maxCol && colNeed <= H - top - bottom - 8;

var sBand = scaleOf(bandBox);
var sSide = sideOk ? scaleOf(sideBox) : null;
var useSide = sSide !== null && sBand !== null && sSide >= sBand * minGain;
if (sSide !== null && !useSide) scaleOf(bandBox);

var lay = { mode: useSide ? 'side' : 'band', scale: { band: sBand, side: sSide } };
if (useSide) {
lay.mapBox = sideBox;
lay.legendX = side === 'left' ? inset : W - inset - lw;
lay.legendY = edge === 'top' ? top + inset : H - lh;
lay.zoom = side === 'left'
? { originX: colW - 4, originY: top + 2, width: Math.max(1, W - colW + 4), height: Math.max(1, H - top - 2) }
: { originX: 0, originY: top + 2, width: Math.max(1, W - colW + 4), height: Math.max(1, H - top - 2) };
lay.clipTop = top;
} else {
lay.mapBox = bandBox;
lay.legendX = edge === 'bottom' && side === 'right' ? W - inset - lw : inset;
lay.legendY = edge === 'top' ? top + inset : H - lh;
lay.zoom = edge === 'top'
? { originX: 0, originY: top + band - 4, width: W, height: Math.max(1, H - (top + band - 4)) }
: { originX: 0, originY: top + 2, width: W, height: Math.max(1, H - band - (top + 2)) };
lay.clipTop = edge === 'top' ? top + band - 4 : top;
}

lay.items = [];
if (useSide) {
var y = edge === 'top' ? lay.legendY + lh + ITEM_GAP : lay.legendY - ITEM_GAP - itemsH;
for (var k = 0; k < sideItems.length; k++) {
var s = sideItems[k];
y += (k ? LINE_GAP : 0) + s.fs;
lay.items.push({ x: lay.legendX, y: y, width: lw, fontSize: Math.max(TYPE_FLOOR, s.fs), lines: s.lines, item: s.it });
y += (s.lines.length - 1) * (s.fs + WRAP_GAP);
}
} else {
var bx = lay.legendX + lw + 12, by = lay.legendY;
for (var b = 0; b < items.length; b++) {
var bfs = fsOf(items[b]);
by += (b ? LINE_GAP : 2) + bfs;
lay.items.push({ x: bx, y: by, width: Math.max(0, W - bx - 8), fontSize: Math.max(TYPE_FLOOR, bfs), lines: [String(items[b].text)], item: items[b] });
}
}

var fitLine = function (sel, room, text) {
if (typeof d3.llmFitLabel === 'function') { d3.llmFitLabel(sel, room, { pad: 0, text: text }); return; }
var fs = parseFloat(sel.attr('font-size')) || TYPE_FLOOR;
if (run(text, fs) <= room) { sel.text(text); return; }
var n = Math.max(0, Math.floor(room / (fs * 0.6)) - 1);
sel.text(n > 0 ? text.slice(0, n) + '\u2026' : '');
};
lay.drawItems = function (parent, d) {
d = d || {};
var fg = d.fg || '#333', yEnd = lay.legendY + lh;
if (!parent || !lay.items.length) return yEnd;
var g = parent.append('g').attr('class', 'llm-legend-caption');
for (var i = 0; i < lay.items.length; i++) {
var p = lay.items[i], it = p.item, fs = Math.max(TYPE_FLOOR, p.fontSize), sw = swatchRoom(it, fs);
var ig = g.append('g').attr('transform', 'translate(' + p.x + ',' + p.y + ')');
if (it.swatch) {
var sq = Math.round(fs * 0.8);
ig.append('rect').attr('y', 1 - sq).attr('width', sq).attr('height', sq)
.attr('fill', it.swatch).attr('stroke', '#ccc').attr('stroke-width', 0.5);
}
var full = String(it.text), cut = false, first = null;
for (var j = 0; j < p.lines.length; j++) {
var t = ig.append('text').attr('x', sw).attr('y', j * (fs + WRAP_GAP))
.attr('font-size', fs).attr('fill', fg);
if (it.opacity != null) t.attr('fill-opacity', it.opacity);
fitLine(t, Math.max(0, p.width - sw), p.lines[j]);
if (t.text() !== p.lines[j]) cut = true;
if (!first) first = t;
}
if (first && (cut || p.lines.length > 1)) first.append('title').text(full);
yEnd = p.y + (p.lines.length - 1) * (fs + WRAP_GAP) + Math.round(fs * 0.25);
}
return yEnd;
};
return lay;
};
// @requires llmText
d3.llmFilterScope = function (options) {
var f = options && options.filterScope;
var vals = [];
if (f && typeof f === 'object' && f.values && typeof f.values.length === 'number' && typeof f.values !== 'string') {
for (var i = 0; i < f.values.length; i++) {
var v = f.values[i];
if (v !== null && v !== undefined && String(v).trim() !== '' && vals.indexOf(String(v)) < 0) vals.push(String(v));
}
}
var label = '';
if (f && typeof f === 'object' && typeof f.label === 'string' && f.label.trim()) label = f.label.trim();
else if (vals.length === 1) label = d3.llmText('d3.filterscope.only', '{value} only', { value: vals[0] });
else if (vals.length === 2) label = d3.llmText('d3.segments.and', '{first} and {second}', { first: vals[0], second: vals[1] });
else if (vals.length > 2) label = d3.llmText('d3.filterscope.and_more', '{first} and {count} more', { first: vals[0], count: vals.length - 1 }, vals.length - 1);
var narrowed = label !== '';
return {
narrowed: narrowed,
label: label,
field: f && typeof f === 'object' && typeof f.field === 'string' ? f.field : '',
values: vals,
title: function (name) { return narrowed ? String(name) + ' \u00b7 ' + label : String(name); },
baseline: function (key, compute) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = String(key);
if (!narrowed) {
var v = typeof compute === 'function' ? compute() : compute;
if (typeof v === 'number' && isFinite(v)) mem[k] = v;
return { value: v, cohort: 'all' };
}
if (Object.prototype.hasOwnProperty.call(mem, k)) return { value: mem[k], cohort: 'all' };
return { value: typeof compute === 'function' ? compute() : compute, cohort: 'shown' };
},
domain: function (key, values) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = 'domain:' + String(key), shown = [];
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n !== null && n !== undefined && n !== '' && typeof n !== 'boolean' && isFinite(+n)) shown.push(+n);
}
var out = function (v, cohort) {
var lo = null, hi = null;
for (var j = 0; j < v.length; j++) { if (lo === null || v[j] < lo) lo = v[j]; if (hi === null || v[j] > hi) hi = v[j]; }
return { values: v, lo: lo, hi: hi, cohort: cohort };
};
if (!narrowed) {
if (shown.length) mem[k] = shown.slice();
return out(shown, 'all');
}
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null;
if (kept && typeof kept.length === 'number' && kept.length) {
var full = out(kept, 'all'), wide = kept.slice();
for (var w = 0; w < shown.length; w++) if (shown[w] < full.lo || shown[w] > full.hi) wide.push(shown[w]);
return out(wide, 'all');
}
return out(shown, 'shown');
},
track: function (key, kind, values, reference) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var kd = kind === 'span' || kind === 'range' ? kind : 'top';
var k = 'track:' + kd + ':' + String(key), ref = +reference, lo = null, hi = null, wide = null;
if (kd === 'span' && !isFinite(ref)) ref = 0;
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n === null || n === undefined || n === '' || typeof n === 'boolean' || !isFinite(+n)) continue;
n = kd === 'span' ? Math.abs(+n - ref) : +n;
if (lo === null || n < lo) lo = n;
if (hi === null || n > hi) hi = n;
}
var shown = kd === 'range' ? (lo === null ? null : [lo, hi]) : (hi || 1);
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null, cohort = 'all', widened = false;
if (!narrowed) {
if (shown !== null) mem[k] = kd === 'range' ? shown.slice() : shown;
wide = shown;
} else if (kd === 'range' ? kept && kept.length === 2 : typeof kept === 'number' && isFinite(kept)) {
if (kd === 'range') {
wide = kept.slice();
if (shown !== null && shown[0] < wide[0]) { wide[0] = shown[0]; widened = true; }
if (shown !== null && shown[1] > wide[1]) { wide[1] = shown[1]; widened = true; }
} else {
wide = kept;
if (shown > kept) { wide = shown; widened = true; }
}
} else {
wide = shown;
cohort = 'shown';
}
if (kd === 'top') return { domain: [0, wide], lo: 0, hi: wide, value: wide, cohort: cohort, widened: widened };
if (kd === 'span') return { domain: [-wide, wide], lo: -wide, hi: wide, value: wide, cohort: cohort, widened: widened };
if (wide === null) return { domain: [0, 1], lo: null, hi: null, value: null, cohort: cohort, widened: widened };
var pad = wide[1] > wide[0] ? 0 : (Math.abs(wide[0]) * 0.01 || 0.01);
return { domain: [wide[0] - pad, wide[1] + pad], lo: wide[0], hi: wide[1], value: null, cohort: cohort, widened: widened };
},
among: function (text) { return narrowed ? String(text) + ' (' + label + ')' : String(text); }
};
};
d3.llmFilterScope.reference = function (field, values) {
var w = String(field == null ? '' : field).replace(/YoY|MoM|QoQ|WoW/g, function (m) { return ' ' + m.toLowerCase() + ' '; })
.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ');
if (/\b(growth|yoy|mom|qoq|wow|change|gap|variance|delta)\b/i.test(w)) return { value: 0, kind: 'zero' };
if (!/\b(attainment|achievement|of (target|plan|quota|budget|goal)|vs\.? (target|plan|quota|budget|goal)|to (target|plan|quota|goal))\b/i.test(w)) return null;
var v = [];
for (var i = 0; values && i < values.length; i++) { var n = values[i]; if (n !== null && n !== undefined && n !== '' && isFinite(+n)) v.push(+n); }
for (var k = 0; k < v.length; k++) if (v[k] < 0) return { value: 0, kind: 'zero' };
v.sort(function (a, b) { return a - b; });
var md = v.length ? (v.length % 2 ? v[(v.length - 1) / 2] : (v[v.length / 2 - 1] + v[v.length / 2]) / 2) : 1;
return { value: md < 10 ? 1 : 100, kind: 'goal' };
};
d3.llmDisplayName = function (name) {
var s = name === null || name === undefined ? '' : String(name);
if (!s || /\s/.test(s)) return s.trim();
var t = s.replace(/[_]+/g, ' ');
if (/^[a-z0-9]+(?:-+[a-z0-9]+)+$/.test(t)) t = t.replace(/-+/g, ' ');
t = t.trim();
if (t !== s) return t.charAt(0).toUpperCase() + t.slice(1);
var parts = [];
var re = /[a-z][A-Z][a-z]+|[A-Z][a-z][A-Z](?![a-z])|[A-Z]+[0-9]+|[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|[0-9]+[A-Z](?![a-z0-9])|[0-9]+|[^A-Za-z0-9]+/g;
var m;
while ((m = re.exec(s)) !== null) {
if (m[0] === '') { re.lastIndex++; continue; }
parts.push(m[0]);
}
if (parts.length < 2 || parts.join('') !== s) return s;
var out = '';
for (var i = 0; i < parts.length; i++) {
var punct = /^[^A-Za-z0-9]+$/.test(parts[i]), prevPunct = i > 0 && /^[^A-Za-z0-9]+$/.test(parts[i - 1]);
out += i === 0 || punct || prevPunct ? parts[i] : ' ' + parts[i];
}
return out.trim();
};


function render(container, data, options) {
  container.replaceChildren();
  const TYPE_FLOOR = 10;
  const columns = data.columns, rows = data.rows;
  const W = options.width, H = options.height;
  const CF = Math.max(TYPE_FLOOR, Math.min(14, Math.round(Math.min(W, H) / 55)));
  const SUB_FS = Math.max(TYPE_FLOOR, CF - 1), SMALL_FS = Math.max(TYPE_FLOOR, CF - 2);
  const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  const fmt = new Intl.NumberFormat(options.cultureCode, { maximumSignificantDigits: 4 });
  const geo = options.geo;
  const themeFg = options.themeFg || 'currentColor';

  const ci = n => columns.findIndex(c => c.name === n);
  const isoIdx = ci('__geoIso__'), idxIdx = ci('__rowIdx__');
  const hdiI = ci('HDI'), giniI = ci('GiniIndex'), cIdx = ci('Country');
  if (hdiI < 0) throw new Error('INVALID:column "HDI" not found');
  if (giniI < 0) throw new Error('INVALID:column "GiniIndex" not found');
  if (cIdx < 0) throw new Error('INVALID:column "Country" not found');
  const xIdx = hdiI, yIdx = giniI;
  const xName = d3.llmDisplayName(columns[xIdx].name), yName = d3.llmDisplayName(columns[yIdx].name);

  const numOf = v => (v == null || v === '' || !isFinite(+v)) ? null : +v;
  const byIso = new Map();
  for (let r = 0; r < rows.length; r++) {
    const row = rows[r], iso = isoIdx >= 0 ? row[isoIdx] : null;
    if (iso == null || iso === '') continue;
    let g = byIso.get(iso);
    if (!g) byIso.set(iso, g = { iso: iso, label: row[cIdx], x: null, y: null, xs: [], ys: [], idx: [] });
    const xv = numOf(row[xIdx]), yv = numOf(row[yIdx]);
    if (xv != null) g.xs.push(xv);
    if (yv != null) g.ys.push(yv);
    g.idx.push(idxIdx >= 0 ? row[idxIdx] : r);
  }

  if (!geo || !geo.features || byIso.size === 0) {
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('fill', themeFg)
      .text(options.noDataText || 'No data to display');
    return;
  }

  const agg = a => {
    const m = (options.aggregation || '').toLowerCase();
    if (m === 'median') return d3.median(a);
    if (m === 'min') return d3.min(a);
    if (m === 'max') return d3.max(a);
    if (m === 'count') return a.length;
    if (m === 'distinct') return new Set(a).size;
    if (m === 'sum') return d3.sum(a);
    return d3.mean(a);
  };
  byIso.forEach(g => { g.x = g.xs.length ? agg(g.xs) : null; g.y = g.ys.length ? agg(g.ys) : null; });
  const featById = new Map(geo.features.map(f => [f.id, f]));
  const matched = [];
  byIso.forEach(g => { const f = featById.get(g.iso); if (f) matched.push(f); });

  const regions = Array.from(byIso.values());
  const biv = d3.llmBivariate({
    x: regions.map(g => g.x), y: regions.map(g => g.y), xLabel: xName, yLabel: yName,
    colorScaleLow: options.colorScaleLow, colorScaleHigh: options.colorScaleHigh,
    palettePrimary: (options.palette && options.palette.length && options.palette[0]) || '#3182bd',
    xRef: undefined, yRef: undefined,
    canvas: options
  });

  const cell = Math.max(10, Math.min(16, Math.round(Math.min(W, H) / 32)));
  const lsz = biv.legendSize(cell, CF);
  const degrade = (lsz.height + 16) > H * 0.34;
  const LEGW = 120, LEGH = 8;
  const legendBand = degrade ? (8 + LEGH + 16 + LEGH + 6) : (8 + lsz.height + 4);
  const land = biv.landFill(options.geoLandColor);
  const noData = options.geoNoDataColor ? biv.landFill(options.geoNoDataColor) : land;
  let ndCount = 0; byIso.forEach(g => { if (g.x == null || g.y == null) ndCount++; });
  const unit = d3.llmPlaceUnit(data);
  const degradeText = 'Tile too short for the two-way legend - shading by ' + xName + ' only';
  const capItems = degrade
    ? [{ text: degradeText, fontSize: SUB_FS, opacity: 0.8 }]
    : [{ text: biv.captionText, fontSize: CF, opacity: 0.85 },
       { text: unit.count(biv.paired) + ' in ' + (9 - biv.emptyCells) + ' of 9 cells' + (biv.emptyCells ? ' (' + biv.emptyCells + ' empty)' : ''), fontSize: SUB_FS, opacity: 0.7 }]
        .concat(biv.forcedNote ? [{ text: biv.forcedNote, fontSize: SUB_FS, opacity: 0.7 }] : [])
        .concat(ndCount > 0 && noData !== land ? [{ text: 'no data', fontSize: SMALL_FS, swatch: noData }] : []);
  const legendBox = degrade ? { width: LEGW, height: legendBand - 8 } : { width: biv.legendSize(cell, SUB_FS).width, height: lsz.height };
  const polyOf = fs => ({ type: 'FeatureCollection', features: fs.filter(f => f.geometry && f.geometry.type !== 'Point') });
  const proj = d3.geoNaturalEarth1();
  const worldFit = (box, clipTop) => d3.llmWorldFit(proj, { geo: geo, regions: matched, width: W, height: H - 10,
    viewport: [W, H], box: box, fitPolygons: true, clipTop: clipTop });
  const lay = d3.llmLegendLayout({ width: W, height: H, legend: legendBox, band: legendBand, items: capItems,
    fit: box => worldFit(box, 0).projection.scale() });
  const wf = worldFit(lay.mapBox, lay.clipTop);
  const path = wf.path;

  const fillFor = g => {
    if (!g) return land;
    if (degrade) return g.x == null ? noData : biv.primaryColor(g.x);
    return (g.x == null || g.y == null) ? noData : biv.colorFor(g.x, g.y);
  };

  const z = d3.llmGeoZoom(svg, { width: lay.zoom.width, height: lay.zoom.height, originX: lay.zoom.originX, originY: lay.zoom.originY,
    themeFg: themeFg, backgroundColor: options.backgroundColor, fontSize: CF, maxScale: 8 });
  const gMap = z.group({ stroke: 0.5, dotStroke: 0.7 });
  wf.clip(svg, gMap);
  const cxy = (c, i) => (c && isFinite(c[i]) ? Math.round(c[i] * 10) / 10 : null);
  gMap.selectAll('path').data(polyOf(geo.features).features, f => f.id).join('path')
    .attr('d', path)
    .attr('class', f => byIso.has(f.id) ? 'd3-mark' : null)
    .style('cursor', f => byIso.has(f.id) ? 'pointer' : null)
    .attr('data-row-idx', f => byIso.has(f.id) ? byIso.get(f.id).idx.join(',') : null)
    .attr('data-cx', f => byIso.has(f.id) ? cxy(path.centroid(f), 0) : null)
    .attr('data-cy', f => byIso.has(f.id) ? cxy(path.centroid(f), 1) : null)
    .attr('fill', f => fillFor(byIso.get(f.id)))
    .attr('stroke', options.backgroundColor || options.themeBg || '#fff').attr('stroke-width', 0.5)
    .each(function (f) {
      const g = byIso.get(f.id), e = g && !degrade && g.x != null && g.y != null ? biv.edgeFor(g.x, g.y) : null;
      if (e) d3.select(this).attr('stroke', e.stroke).attr('stroke-width', e.width)
        .attr('vector-effect', 'non-scaling-stroke').attr('data-llm-edge', 'low-low').raise();
    });

  const pts = matched.filter(f => f.geometry && f.geometry.type === 'Point');
  const prAuto = Math.max(3, Math.min(7, Math.round(Math.min(W, H) / 90)));
  const prSet = +options.geoPointRadiusPx;
  const pr = (isFinite(prSet) && prSet > 0) ? Math.max(1, Math.min(24, prSet)) : prAuto;
  gMap.selectAll('circle').data(pts, f => f.id).join('circle')
    .attr('class', 'd3-mark')
    .style('cursor', 'pointer')
    .attr('cx', f => proj(f.geometry.coordinates)[0]).attr('cy', f => proj(f.geometry.coordinates)[1])
    .attr('r', pr)
    .attr('data-row-idx', f => byIso.get(f.id).idx.join(','))
    .attr('data-cx', f => proj(f.geometry.coordinates)[0]).attr('data-cy', f => proj(f.geometry.coordinates)[1])
    .attr('fill', f => fillFor(byIso.get(f.id)))
    .attr('stroke', themeFg).attr('stroke-opacity', 0.6).attr('stroke-width', 0.7);

  const partText = (name, v, bin, axis) => name + ' ' + (v == null ? 'no data' : fmt.format(v) + ' (' + biv.thirdName(bin, axis) + ')');
  const tipText = g => {
    if (g.x == null && g.y == null) return g.label + ' - no data';
    return g.label + ' - ' + partText(xName, g.x, g.x == null ? null : biv.xBin(g.x), 'x') + ' | ' + partText(yName, g.y, g.y == null ? null : biv.yBin(g.y), 'y')
      + (g.idx.length > 1 ? ' | ' + g.idx.length + ' rows' : '');
  };
  if (options.allowTooltips !== false) {
    gMap.selectAll('.d3-mark').append('title').text(f => tipText(byIso.get(f.id)));
  }

  const unm = options.geoUnmatched && options.geoUnmatched.count;
  if (unm > 0) {
    const unmText = unit.count(unm) + ' unmatched';
    const unmG = svg.append('g').attr('class', 'lch-caption');
    const unmT = unmG.append('text').attr('x', 8).attr('y', H - 12).attr('font-size', CF).attr('fill', themeFg);
    d3.llmFitLabel(unmT, W - 16, { pad: 0, text: unmText });
    if (unmT.text() !== unmText) unmG.append('title').text(unmText);
  }

  const LEGX = lay.legendX, LEGY = lay.legendY;
  if (!degrade) {
    const L = biv.drawLegend(svg, { x: LEGX, y: LEGY, cell: cell, fontSize: SUB_FS, themeFg: themeFg });
    if (lay.mode === 'side') {
      lay.drawItems(svg, { fg: themeFg });
    } else {
      const tx = LEGX + L.width + 12;
      const cap = svg.append('g').attr('transform', 'translate(' + tx + ',' + (LEGY + CF + 2) + ')');
      const capRoom = W - tx - 8;
      const capT = cap.append('text').attr('font-size', CF).attr('fill', themeFg).attr('fill-opacity', 0.85);
      d3.llmFitLabel(capT, capRoom, { pad: 0, text: biv.captionText });
      if (capT.text() !== biv.captionText) capT.append('title').text(biv.captionText);
      cap.append('text').attr('y', CF + 4).attr('font-size', SUB_FS).attr('fill', themeFg).attr('fill-opacity', 0.7)
        .text(unit.count(biv.paired) + ' in ' + (9 - biv.emptyCells) + ' of 9 cells' + (biv.emptyCells ? ' (' + biv.emptyCells + ' empty)' : ''));
      if (biv.forcedNote) {
        const fnT = cap.append('text').attr('y', 2 * CF + 8).attr('font-size', SUB_FS).attr('fill', themeFg).attr('fill-opacity', 0.7);
        d3.llmFitLabel(fnT, capRoom, { pad: 0, text: biv.forcedNote });
        if (fnT.text() !== biv.forcedNote) fnT.append('title').text(biv.forcedNote);
      }
      if (ndCount > 0 && noData !== land) {
        const S = cap.append('g').attr('transform', 'translate(0,' + (biv.forcedNote ? 3 * CF + 12 : 2 * CF + 8) + ')');
        S.append('rect').attr('width', LEGH).attr('height', LEGH).attr('fill', noData).attr('stroke', themeFg).attr('stroke-opacity', 0.4).attr('stroke-width', 0.5);
        S.append('text').attr('x', LEGH + 4).attr('y', LEGH - 1).attr('font-size', SMALL_FS).attr('fill', themeFg).text('no data');
      }
    }
  } else {
    const xsAll = regions.map(g => g.x).filter(v => v != null);
    const lo = xsAll.length ? d3.min(xsAll) : 0, hi = xsAll.length ? d3.max(xsAll) : 1;
    const gid = 'llmgeo-' + Math.abs((W * 131 + H) | 0);
    const lg = svg.append('defs').append('linearGradient').attr('id', gid);
    lg.append('stop').attr('offset', '0%').attr('stop-color', biv.colors[0]);
    lg.append('stop').attr('offset', '100%').attr('stop-color', biv.colors[2]);
    const L = svg.append('g').attr('transform', 'translate(' + LEGX + ',' + LEGY + ')');
    L.append('rect').attr('width', LEGW).attr('height', LEGH).attr('fill', 'url(#' + gid + ')').attr('stroke', themeFg).attr('stroke-opacity', 0.4).attr('stroke-width', 0.5);
    L.append('text').attr('y', LEGH + 12).attr('font-size', SMALL_FS).attr('fill', themeFg).text(fmt.format(lo));
    L.append('text').attr('x', LEGW).attr('y', LEGH + 12).attr('text-anchor', 'end').attr('font-size', SMALL_FS).attr('fill', themeFg).text(fmt.format(hi));
    if (lay.mode === 'side') lay.drawItems(svg, { fg: themeFg });
    else {
      const t = svg.append('text').attr('x', LEGX + LEGW + 12).attr('y', LEGY + LEGH + 2).attr('font-size', SUB_FS).attr('fill', themeFg).attr('fill-opacity', 0.8);
      d3.llmFitLabel(t, W - (LEGX + LEGW + 12) - 8, { pad: 0, text: degradeText });
    }
  }
}

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 🗙