Sum of Revenue by state, one tile each
Which states have the most Sum of Revenue, with every state given equal space?
All fifty states and the District of Columbia, one row each, with total revenue, total orders and a return rate. Revenue runs from about half a million in the smallest state to over thirty million in the largest, and the return rate from 2.1 to 12, so revenue against return rate gives a bivariate map places where the two disagree. Also a fit for a hex-tile cartogram, where every state gets the same shape and the small ones stay readable.
US State Store Metrics: 51 rows, 4 columns. Download the CSV
| State | Sum of Revenue | Sum of Orders | ReturnRate |
|---|---|---|---|
| Alabama | 4050201 | 96362 | 3.0 |
| Alaska | 602775 | 15077 | 2.4 |
| Arizona | 6554752 | 158217 | 10.1 |
| Arkansas | 2838335 | 67901 | 4.6 |
| California | 31787858 | 761846 | 10.2 |
| Colorado | 5229428 | 130259 | 6.4 |
| Connecticut | 3421058 | 83892 | 6.1 |
| Delaware | 958486 | 22943 | 6.8 |
| District of Columbia | 610446 | 15294 | 7.9 |
| Florida | 18145741 | 447529 | 2.5 |

How to read it
Every state gets the same tile, so a small state counts as much as a large one; tiles sit roughly where the states are. California is highest at 31.8M.
The chart's code (71 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.llmValueColumn = function (columns, rows, opts) {
opts = opts || {};
var cols = Array.isArray(columns) ? columns : [];
var data = Array.isArray(rows) ? rows : [];
var isHost = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
return n.indexOf('__') === 0;
};
var taken = {};
(Array.isArray(opts.exclude) ? opts.exclude : []).forEach(function (i) {
if (i != null && i >= 0) taken[i] = 1;
});
var coordinates = [];
if (opts.excludeCoordinates) {
var coordWords = d3.llmValueColumn.nameWords;
var allLongitudes = function (ci) {
var seenL = 0;
for (var rr = 0; rr < data.length; rr++) {
var lv = data[rr] ? data[rr][ci] : null;
if (lv === null || lv === undefined || lv === '') continue;
lv = +lv; seenL++;
if (!isFinite(lv) || lv < -180 || lv > 180) return false;
}
return seenL > 0;
};
cols.forEach(function (c, ci) {
if (!c || isHost(c)) return;
var declared = String(c.semanticType || c.dataCategory || '').toLowerCase();
var w = coordWords(c.name);
if (declared === 'latitude' || declared === 'longitude'
|| w.some(function (t) { return /^(lat|latitude|lon|lng|longitude)$/.test(t); })
|| (w.indexOf('long') >= 0 && allLongitudes(ci))) {
taken[ci] = 1;
coordinates.push(String(c.name));
}
});
}
var NUMERIC_TYPES = { integer: 1, decimal: 1, double: 1, float: 1, single: 1,
number: 1, int64: 1, int32: 1, currency: 1, money: 1 };
var isNumericCol = function (c, i) {
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (dt) return NUMERIC_TYPES[dt] === 1;
var seen = 0, num = 0;
for (var r = 0; r < data.length && seen < 50; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
if (typeof v !== 'boolean' && isFinite(+v)) num++;
}
return seen > 0 && num === seen;
};
var isRegionCode = function (c) {
var k = (c && c.geoKind != null) ? String(c.geoKind).toLowerCase() : '';
if (!k) return false;
return k.indexOf('zip') === 0 || k.indexOf('us-zip') === 0 || k.indexOf('us-state') === 0 ||
k.indexOf('us-county') === 0 || k.indexOf('us-fips') === 0 || k.indexOf('fips') === 0 ||
k.indexOf('country-') === 0 || k.indexOf('iso-') === 0;
};
var ID_TOKENS = { id: 1, ids: 1, identifier: 1, code: 1, codes: 1, zip: 1, zipcode: 1,
postal: 1, postcode: 1, fips: 1, guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1,
isbn: 1, key: 1, num: 1, number: 1, no: 1, ref: 1, serial: 1, barcode: 1,
account: 1, acct: 1, vin: 1, imei: 1, ssn: 1 };
var nameLooksLikeId = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
if (!n) return false;
var parts = n.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^A-Za-z0-9]+/);
for (var p = 0; p < parts.length; p++) {
if (parts[p] && ID_TOKENS[parts[p].toLowerCase()] === 1) return true;
}
return false;
};
var looksLikeKeyData = function (c, i) {
var seen = 0, ints = 0, vals = {}, distinct = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
var num = +v;
if (isFinite(num) && Math.floor(num) === num) ints++;
var kk = String(v);
if (vals[kk] !== 1) { vals[kk] = 1; distinct++; }
}
return seen >= 8 && ints === seen && (distinct / seen) >= 0.9;
};
var isIdentifierCol = function (c, i) {
if (!c) return false;
if (isRegionCode(c)) return true;
return nameLooksLikeId(c) && looksLikeKeyData(c, i);
};
var STRONG_ID_HEADS = { id: 1, ids: 1, identifier: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1,
guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1, isbn: 1, serial: 1, barcode: 1, vin: 1, imei: 1, ssn: 1 };
var WEAK_ID_TAILS = { code: 1, codes: 1, number: 1, num: 1, no: 1, nbr: 1, ref: 1 };
var allIntegers = function (i) {
var seen = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
}
return seen > 0;
};
var COUNT_WORDS = { count: 1, countd: 1, distinct: 1, recuento: 1, contagem: 1, anzahl: 1, aantal: 1, conteggio: 1,
antal: 1, antall: 1, lukumaara: 1, 'lukum\u00e4\u00e4r\u00e4': 1, pocet: 1, 'po\u010det': 1, liczba: 1 };
var NUMBER_OF = { number: 1, num: 1, no: 1, nombre: 1 };
var OF_WORDS = { of: 1, de: 1, du: 1, des: 1 };
var countsSomething = function (c, w) {
if (/^\s*#/.test(String(c.name))) return true;
for (var k = 0; k < w.length; k++) {
if (COUNT_WORDS[w[k]] === 1) return true;
if (NUMBER_OF[w[k]] === 1 && OF_WORDS[w[k + 1]] === 1) return true;
}
return false;
};
var CODE_WORDS = { zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1, code: 1, iso: 1, geoid: 1 };
var isFlaggedIdentifier = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name);
if (isRegionCode(c)) for (var cw = 0; cw < w.length; cw++) if (CODE_WORDS[w[cw]] === 1) return true;
if (!w.length || countsSomething(c, w)) return false;
var head = w[w.length - 1];
if (WEAK_ID_TAILS[head] === 1 && w.length > 1 && STRONG_ID_HEADS[w[w.length - 2]] === 1) head = w[w.length - 2];
if (!(STRONG_ID_HEADS[head] === 1 || w[0] === 'id')) return false;
return allIntegers(i);
};
var DATE_KEY_WORDS = { key: 1, date: 1, period: 1, month: 1, yyyymm: 1, yyyymmdd: 1, ym: 1, ymd: 1 };
var isDateKey = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name), named = false;
for (var k = 0; k < w.length; k++) if (DATE_KEY_WORDS[w[k]] === 1) { named = true; break; }
if (!named) return false;
var seen = 0, ymd = 0, ym = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
if (n >= 19000101 && n <= 21001231) {
var mo = Math.floor(n / 100) % 100, dd = n % 100;
if (mo >= 1 && mo <= 12 && dd >= 1 && dd <= 31) ymd++;
} else if (n >= 190001 && n <= 210012) {
var m2 = n % 100;
if (m2 >= 1 && m2 <= 12) ym++;
}
}
return seen > 0 && (ymd === seen || ym === seen);
};
var isTextMeasure = function (c) {
if (!c || !c.isMeasure) return false;
var dt = (c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (!dt || NUMERIC_TYPES[dt] === 1 || dt === 'datetime' || dt === 'date' || dt === 'boolean') return false;
if (c.stdDev != null || c.sum != null || c.avgValue != null) return false;
return String(c.valueNature || '').toLowerCase() !== 'continuous';
};
var valueIndex = -1, resolvedBy = 'count';
var skipped = [];
var skippedText = []; // measures passed over because they hold text (isTextMeasure)
if (opts.prefer != null) {
var want = opts.prefer;
for (var q = 0; q < cols.length; q++) {
if (!cols[q]) continue;
if (q === want || (typeof want === 'string' && String(cols[q].name) === want)) {
if (!taken[q] && !isHost(cols[q])) { valueIndex = q; resolvedBy = 'preferred'; }
break;
}
}
}
var refused = {};
var notAQuantity = function (c, ci) {
if (refused[ci] !== undefined) return refused[ci];
return (refused[ci] = isTextMeasure(c) ? 'text' : ((isFlaggedIdentifier(c, ci) || isDateKey(c, ci)) ? 'key' : ''));
};
var IDENT_LAST = { id: 1, ids: 1, uuid: 1, guid: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postalcode: 1, ssn: 1,
code: 1, codes: 1, sku: 1, isbn: 1, msisdn: 1, imei: 1 };
var ORDINAL_WORDS = { hour: 1, hr: 1, day: 1, dow: 1, dom: 1, weekday: 1, week: 1, wk: 1, woy: 1, month: 1, mth: 1,
quarter: 1, qtr: 1, year: 1, yr: 1, semester: 1, trimester: 1, decade: 1, period: 1, fiscal: 1,
fy: 1, rank: 1, level: 1, lvl: 1, tier: 1, grade: 1, band: 1, decile: 1, percentile: 1,
quartile: 1, quintile: 1, score: 1, rating: 1, stars: 1, step: 1, stage: 1, phase: 1, round: 1,
wave: 1, episode: 1, chapter: 1, age: 1, cohort: 1, generation: 1, seniority: 1, position: 1,
sequence: 1, seq: 1, priority: 1 };
var looksContinuous = function (c, i) {
var w = d3.llmValueColumn.nameWords(c.name);
if (w.length && IDENT_LAST[w[w.length - 1]] === 1) return false;
if (d3.llmValueColumn.localizedIdentifierWord(c.name)) return false;
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
var hasFraction = false, seenV = {}, distinct = 0, nonblank = 0, mn = Infinity, mx = -Infinity;
for (var r = 0; r < data.length; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n)) continue;
nonblank++;
var key = String(v);
if (seenV[key] !== 1) { seenV[key] = 1; distinct++; }
if (n < mn) mn = n;
if (n > mx) mx = n;
if (Math.floor(n) !== n) hasFraction = true;
}
if (nonblank === 0) return false;
var fractional = hasFraction || dt === 'decimal' || dt === 'double' || dt === 'float' || dt === 'single'
|| dt === 'currency' || dt === 'money';
var span = mx - mn + 1, density = span > 0 ? distinct / span : 1;
if (density >= 0.9) {
for (var k = 0; k < w.length; k++) if (ORDINAL_WORDS[w[k]] === 1 && distinct <= 120) return false;
if (mn >= 1900 && mx <= 2100) return false;
if (mn >= 0 && mx <= 20) return false;
}
return distinct > 12 && (fractional || distinct >= 100 || distinct / nonblank >= 0.30);
};
var measures = [];
for (var mi = 0; mi < cols.length; mi++) {
if (taken[mi] || !cols[mi] || !cols[mi].isMeasure || isHost(cols[mi])) continue;
if (!notAQuantity(cols[mi], mi)) measures.push(mi);
}
var measuresInferred = false;
var anyFlagged = false, anyProfiled = false;
for (var fi = 0; fi < cols.length; fi++) {
var fc = cols[fi];
if (!fc || isHost(fc)) continue;
if (fc.isMeasure) anyFlagged = true;
if (fc.valueNature != null || fc.distinctCount != null) anyProfiled = true;
}
if (!anyFlagged && !anyProfiled) {
for (var ni = 0; ni < cols.length; ni++) {
if (taken[ni] || !cols[ni] || isHost(cols[ni])) continue;
if (!isNumericCol(cols[ni], ni)) continue;
if (isIdentifierCol(cols[ni], ni) || isDateKey(cols[ni], ni)) continue;
if (!looksContinuous(cols[ni], ni)) continue;
measures.push(ni);
}
measuresInferred = measures.length > 0;
}
if (valueIndex < 0) {
for (var i = 0; i < cols.length; i++) {
if (taken[i]) continue;
if (!cols[i] || !cols[i].isMeasure || isHost(cols[i])) continue;
var why = notAQuantity(cols[i], i);
if (why === 'text') { skippedText.push(String(cols[i].name)); continue; }
if (why === 'key') { skipped.push(String(cols[i].name)); continue; }
valueIndex = i; resolvedBy = 'measure'; break;
}
}
if (valueIndex < 0) {
for (var j = 0; j < cols.length; j++) {
if (taken[j] || !cols[j] || isHost(cols[j])) continue;
if (!isNumericCol(cols[j], j)) continue;
if (refused[j] === 'key') continue; // a flagged key rule 1 already refused and named
if (isIdentifierCol(cols[j], j) || isDateKey(cols[j], j)) {
skipped.push(String(cols[j].name));
continue;
}
valueIndex = j; resolvedBy = 'numeric'; break;
}
}
var labelIndex = -1;
for (var k = 0; k < cols.length; k++) {
if (taken[k] || !cols[k] || isHost(cols[k]) || k === valueIndex) continue;
labelIndex = k; break;
}
var isCount = valueIndex < 0;
var nameOf = function (idx) {
var c = cols[idx];
return (c && c.name != null) ? String(c.name) : '';
};
return {
valueIndex: valueIndex,
valueName: isCount ? (opts.countLabel || 'Rows') : nameOf(valueIndex),
labelIndex: labelIndex,
labelName: labelIndex >= 0 ? nameOf(labelIndex) : '',
isCount: isCount,
resolvedBy: resolvedBy,
skipped: skipped,
skippedText: skippedText,
coordinates: coordinates,
measures: measures,
measuresInferred: measuresInferred,
valueOf: function (row) {
if (isCount) return 1;
if (!row) return null;
var v = row[valueIndex];
if (v == null || v === '' || typeof v === 'boolean') return null;
var n = +v;
return isFinite(n) ? n : null;
}
};
};
d3.llmValueColumn.nameWords = function (name, opts) {
var s = String(name == null ? '' : name);
try { s = s.normalize('NFC'); } catch (e) { /* an unpaired surrogate: read it as it stands */ }
s = s.replace(/([\p{Ll}\p{Nd}])(?=\p{Lu})/gu, '$1 ').toLowerCase();
return s.split(opts && opts.digits ? /[^\p{L}\p{M}\p{N}]+/u : /[^\p{L}\p{M}]+/u)
.filter(function (w) { return w.length > 0; });
};
d3.llmValueColumn.localizedIdentifierWord = (function () {
var WORDS = {
de: ['nr', 'nummer', 'kennung', 'kennziffer', 'plz', 'postleitzahl'],
nl: ['nr', 'nummer'],
sv: ['nr', 'nummer'],
da: ['nr', 'nummer'],
nb: ['nr', 'nummer'],
fi: ['tunnus', 'koodi', 'nro'],
hu: ['azonos\u00edt\u00f3', 'k\u00f3d'],
tr: ['kod', 'kodu', 'numaras\u0131', 'numarasi'],
zh: ['\u7f16\u53f7', '\u4ee3\u7801', '\u7f16\u7801', '\u53f7\u7801', '\u90ae\u7f16'],
ja: ['\u756a\u53f7', '\u30b3\u30fc\u30c9'],
ko: ['\ubc88\ud638', '\ucf54\ub4dc'],
hi: ['\u0915\u094b\u0921', '\u0915\u094d\u0930\u092e\u093e\u0902\u0915'],
fr: ['num\u00e9ro'],
es: ['c\u00f3digo'],
pt: ['c\u00f3digo', 'cep'],
it: ['codice'],
pl: ['kod', 'numer'],
cs: ['k\u00f3d', '\u010d\u00edslo'],
sk: ['k\u00f3d', '\u010d\u00edslo'],
hr: ['\u0161ifra', 'oznaka'],
ru: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
uk: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
el: ['\u03ba\u03c9\u03b4\u03b9\u03ba\u03cc\u03c2'],
ar: ['\u0631\u0645\u0632', '\u0643\u0648\u062f', '\u0631\u0642\u0645'],
he: ['\u05e7\u05d5\u05d3'],
id: ['kode', 'nomor'],
vi: ['m\u00e3'],
th: ['\u0e23\u0e2b\u0e31\u0e2a']
};
var HEAD_INITIAL = ['fr', 'es', 'pt', 'it', 'pl', 'cs', 'sk', 'hr', 'ru', 'uk', 'el', 'ar', 'he', 'id', 'vi', 'th'];
var COMPOUNDS = ['nl', 'de', 'sv', 'da', 'nb', 'fi', 'hu'];
var NO_BREAKS = ['zh', 'ja', 'th'];
var UNFOLDED = ['num\u00e9ro'];
var GLUED = { ar: ['\u0627\u0644', '\u0648\u0627\u0644', '\u0628\u0627\u0644', '\u0641\u0627\u0644', '\u0643\u0627\u0644', '\u0644\u0644', '\u0648', '\u0641', '\u0628', '\u0643', '\u0644'], he: ['\u05d4', '\u05d5', '\u05d1', '\u05dc', '\u05de', '\u05e9', '\u05db', '\u05d5\u05d4', '\u05e9\u05d4', '\u05de\u05d4', '\u05d5\u05d1', '\u05d5\u05dc', '\u05d5\u05de', '\u05d1\u05d4', '\u05dc\u05d4'] };
var DEFAULT_PREFIXES = ['somme de', 'suma de', 'soma de', 'summe von', 'som van', 'somma di', 'summa av', 'sum av', 'sum af', 'soucet z', 'suma z', 'totaal van', 'total de', 'toplam', 'osszeg', 'nombre de', 'recuento de', 'contagem de', 'anzahl von', 'aantal van', 'conteggio di', 'antal av', 'lukumaara', 'pocet z', 'sum pa', '\u0441\u0443\u043c\u043c\u0430', '\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e', '\u0441\u0443\u043c\u0430', '\u043a\u0456\u043b\u044c\u043a\u0456\u0441\u0442\u044c', '\u03b1\u03b8\u03c1\u03bf\u03b9\u03c3\u03bc\u03b1', '\u03c0\u03bb\u03b7\u03b8\u03bf\u03c2'];
var DEFAULT_SUFFIXES = ['osszege', 'sucet', '\u7684\u603b\u548c', '\u7684\u8ba1\u6570', '\u306e\u5408\u8a08', '\uc758 \ud569\uacc4'];
var has = function (list, x) { return list.indexOf(x) >= 0; };
var cpLen = function (s) { return Array.from(s).length; };
var STROKE = { '\u0142': 'l', '\u0141': 'L', '\u0131': 'i', '\u00f8': 'o', '\u00d8': 'O', '\u0111': 'd', '\u0110': 'D', '\u00f0': 'd', '\u00d0': 'D' };
var DIGIT_ZEROS = [0x0660, 0x06F0, 0x0966, 0x0E50, 0xFF10];
var foldName = function (s) {
var out = '';
Array.from(s).forEach(function (ch) {
if (STROKE[ch]) { out += STROKE[ch]; return; }
var cp = ch.codePointAt(0);
for (var z = 0; z < DIGIT_ZEROS.length; z++) if (cp >= DIGIT_ZEROS[z] && cp <= DIGIT_ZEROS[z] + 9) { out += String.fromCharCode(0x30 + cp - DIGIT_ZEROS[z]); return; }
if ((cp >= 0xFF21 && cp <= 0xFF3A) || (cp >= 0xFF41 && cp <= 0xFF5A)) { out += String.fromCharCode(cp - 0xFEE0); return; }
var d = ch.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
out += d.length === 1 ? d : ch;
});
return out;
};
var readWords = function (name) {
return String(name == null ? '' : name).normalize('NFC')
.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu, '$1 $2').replace(/[_\-.\/]+/g, ' ')
.replace(/[^\p{L}\p{M}\p{N}\x00-\x7F]/gu, ' ').toLowerCase().split(/\s+/)
.filter(function (w) { return w.length > 0; });
};
var readName = function (name) {
var s = String(name == null ? '' : name).normalize('NFC');
var words = readWords(s), folded = readWords(foldName(s));
return { words: words, folded: folded.length === words.length ? folded : words.map(foldName) };
};
var lowerNfc = function (s) { return s.normalize('NFC').toLowerCase(); };
var alt = function (phrases) {
return phrases.slice().sort(function (a, b) { return b.length - a.length; })
.map(function (t) { return t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+'); }).join('|');
};
var hasCjk = function (t) {
return Array.from(t).some(function (ch) { var c = ch.codePointAt(0); return (c >= 0x2e80 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af); });
};
var PREFIX_RE = new RegExp('^\\s*(?:(?:sum|count|count\\s+distinct|distinct\\s+count)\\s+of\\s+|(?:' + alt(DEFAULT_PREFIXES) + ')\\s+)', 'i');
var SUFFIX_RE = (function () {
var latin = DEFAULT_SUFFIXES.filter(function (l) { return !hasCjk(l); }), cjk = DEFAULT_SUFFIXES.filter(hasCjk), parts = [];
if (latin.length) parts.push('(?:\\s+|\\s*[\u2013\u2014-]\\s*)(' + alt(latin) + ')');
if (cjk.length) parts.push('\\s*(' + alt(cjk) + ')');
return new RegExp('(?:' + parts.join('|') + ')\\s*$', 'i');
})();
var stripAgg = function (name) {
var s = String(name == null ? '' : name), folded = foldName(s);
var m = PREFIX_RE.exec(folded);
if (m) return s.slice(m[0].length).trim();
var sm = SUFFIX_RE.exec(folded);
if (sm && folded.slice(0, sm.index).trim() !== '') return s.slice(0, sm.index).trim();
return s.trim();
};
var endsWithStem = function (word, token, minStem) {
return !!word && !!token && word.length > token.length && word.endsWith(token) && cpLen(word.slice(0, word.length - token.length)) >= minStem;
};
var gluedStems = function (word, lang) {
var out = [], list = GLUED[lang];
if (!word || !list) return out;
list.slice().sort(function (a, b) { return b.length - a.length; }).forEach(function (p) {
if (word.length > p.length && word.startsWith(p)) { var st = word.slice(p.length); if (cpLen(st) >= 2 && out.indexOf(st) < 0) out.push(st); }
});
return out;
};
var readsAs = function (word, token, lang, first) {
if (!word) return false;
if (word === token) return true;
if (has(NO_BREAKS, lang)) {
if (cpLen(token) < 2) return false;
return (first ? word.startsWith(token) : word.endsWith(token)) && word.length > token.length;
}
if (first) return gluedStems(word, lang).indexOf(token) >= 0;
if (lang === 'ko') return /\p{Script=Hangul}/u.test(token) && endsWithStem(word, token, 2);
if (has(COMPOUNDS, lang)) return endsWithStem(word, token, 3);
return false;
};
return function (name) {
var n = String(name == null ? '' : name).trim();
if (!n) return false;
var whole = readName(n), stripped = readName(stripAgg(n));
for (var lang in WORDS) {
var first = has(HEAD_INITIAL, lang), reading = first ? stripped : whole;
for (var t = 0; t < WORDS[lang].length; t++) {
var token = WORDS[lang][t];
var plain = has(UNFOLDED, token) || lang === 'vi';
var words = plain ? reading.words : reading.folded;
if (words.length === 0) continue;
var tok = plain ? lowerNfc(token) : readName(token).folded.join(' ');
if (readsAs(first ? words[0] : words[words.length - 1], tok, lang, first)) return true;
}
}
return false;
};
})();
// @requires llmFilterScope
d3.llmValueRamp = function (cfg) {
var TYPE_FLOOR = 10; // the minimum readable type, px: the legend's labels draw no smaller
cfg = cfg || {};
var num = function (v) { return (v == null || v === '' || !isFinite(+v)) ? null : +v; };
var vals = [];
(cfg.values || []).forEach(function (v) { v = num(v); if (v != null) vals.push(v); });
vals.sort(function (a, b) { return a - b; });
var mid = num(cfg.mid), diverging = mid != null;
var asColour = function (c) {
if (c && typeof c === 'object' && typeof c.formatHex === 'function') return c;
return typeof c === 'string' && c.trim() !== '' && num(c) == null && d3.color(c) ? c : null;
};
var boundLo = asColour(cfg.low) ? null : num(cfg.low), boundHi = asColour(cfg.high) ? null : num(cfg.high);
var low = asColour(cfg.low) || (diverging ? '#b35806' : '#eef3f8'), high = asColour(cfg.high) || (diverging ? '#2166ac' : '#3182bd');
var cvColor = cfg.canvas ? d3.color(cfg.canvas) : 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 && !cfg.highContrast && 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 && !diverging) {
var toHigh = d3.interpolateLab(low, high), s = 0;
while (s < 20 && onPage(d3.lab(toHigh(s / 20)).formatHex()) < 3) s++;
low = offPage(d3.lab(toHigh(s / 20)).formatHex(), 3);
high = offPage(high, Math.max(3, onPage(low) * 2));
}
var midColor = cfg.midColor;
if (!midColor) {
var cv = cfg.canvas ? d3.lab(cfg.canvas) : null, cl = cv && isFinite(cv.l) ? cv.l : null;
if (cl == null && !cfg.highContrast) midColor = '#f7f7f7';
else {
if (cl == null) cl = 100;
var off = cfg.highContrast ? 25 : (cl < 50 ? 18 : 3);
midColor = d3.lab(cl < 50 ? cl + off : cl - off, 0, 0).formatHex();
}
}
var n = vals.length;
var lo = n ? vals[0] : 0, hi = n ? vals[n - 1] : 1;
if (boundLo != null && (!n || boundLo < lo)) lo = boundLo; // a numeric low / high widens the range, never narrows it
if (boundHi != null && (!n || boundHi > hi)) hi = boundHi;
var median = n ? d3.quantile(vals, 0.5) : null, p95 = n ? d3.quantile(vals, 0.95) : null;
var scale = d3.scaleLinear().domain(lo === hi ? [lo - 1, hi] : [lo, hi]).range([low, high]).clamp(true);
var kind = n && lo === hi ? 'constant' : 'linear', edges = [lo, hi], colors = [low, high];
if (diverging) {
var span = Math.max(Math.abs(lo - mid), Math.abs(hi - mid)) || Math.abs(mid) || 1;
edges = [mid - span, mid, mid + span];
colors = [low, midColor, high];
scale = d3.scaleLinear().domain(edges).range([low, midColor, high]).clamp(true);
kind = 'diverging';
} else if (n >= 10 && lo >= 0 && lo !== hi && p95 > 4 * median) {
var inner = [];
for (var q = 1; q < 5; q++) {
var t = vals[Math.floor(q * n / 5)];
if (t > lo && (!inner.length || t > inner[inner.length - 1])) inner.push(t);
}
if (inner.length >= 2) {
var along = d3.scaleLinear().domain([0, inner.length]).range([low, high]);
colors = [];
for (var c = 0; c <= inner.length; c++) colors.push(along(c));
scale = function (v) { return colors[d3.bisectRight(inner, v)]; };
edges = [lo].concat(inner, [hi]);
kind = 'bands';
}
}
var atCentre = function (v) { return kind === 'diverging' && Math.abs(v - mid) <= 1e-9 * Math.max(1, Math.abs(mid)); };
var drawVertical = function (g, w, h, size, fg, op, fmt, o) {
var fs = Math.max(TYPE_FLOOR, size); // floored here too: the caller's size arrives as a parameter
var lx = w + 4, rows = [], widest = 0, k = colors.length;
var a0 = kind === 'diverging' ? edges[0] : lo, a1 = kind === 'diverging' ? edges[edges.length - 1] : hi;
var at = function (f) { return h - Math.max(0, Math.min(1, f)) * h; }; // 0 = the low end, 1 = the high end
var frac = function (v) {
if (kind === 'bands') {
var bi = Math.max(0, Math.min(k - 1, d3.bisectRight(edges, v) - 1));
var sp = edges[bi + 1] - edges[bi];
return (bi + (sp > 0 ? Math.max(0, Math.min(1, (v - edges[bi]) / sp)) : 0)) / k;
}
return a1 > a0 ? (v - a0) / (a1 - a0) : 0.5;
};
var placeY = function (y, text, always, cls) {
var y0 = y - 0.8 * fs, y1 = y + 0.2 * fs;
if (!always && rows.some(function (r) { return y0 < r[1] + 4 && y1 > r[0] - 4; })) return false;
rows.push([y0, y1]);
g.append('text').attr('class', cls || 'llm-value-ramp-label').attr('x', lx).attr('y', y)
.attr('text-anchor', 'start').attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
widest = Math.max(widest, String(text).length * fs * 0.58);
return true;
};
var box = function () {
var bottom = h;
rows.forEach(function (r) { bottom = Math.max(bottom, r[1]); });
return { width: lx + widest, height: bottom };
};
if (kind === 'bands') {
var sh = h / k;
for (var b = 0; b < k; b++) {
var r = g.append('rect').attr('class', 'llm-value-ramp-band').attr('y', (k - 1 - b) * sh).attr('width', w)
.attr('height', sh).attr('fill', colors[b]).attr('data-from', edges[b]).attr('data-to', edges[b + 1]);
if (o.stroke) r.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
} else {
var id = o.id || ('llmramp-' + Math.abs((w * 131 + h * 7) | 0) + '-v' + (kind === 'diverging' ? 'd' : ''));
var lg = g.append('defs').append('linearGradient').attr('id', id)
.attr('x1', '0%').attr('y1', '100%').attr('x2', '0%').attr('y2', '0%');
lg.append('stop').attr('offset', '0%').attr('stop-color', low);
if (kind === 'diverging') lg.append('stop').attr('offset', '50%').attr('stop-color', midColor);
lg.append('stop').attr('offset', '100%').attr('stop-color', high);
var bar = g.append('rect').attr('class', 'llm-value-ramp-bar').attr('width', w).attr('height', h)
.attr('fill', 'url(#' + id + ')');
if (o.stroke) bar.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
if (kind === 'constant') {
placeY(Math.min(h, 0.8 * fs), fmt(lo) + (o.constantText || ''), true);
return box();
}
var topY = 0.8 * fs, botY = Math.max(h, topY + fs + 4);
placeY(topY, fmt(a1), true);
placeY(botY, fmt(a0), true);
if (o.highLabel) placeY(topY + fs + 2, o.highLabel, true, 'llm-value-ramp-side');
if (o.lowLabel) placeY(botY + fs + 2, o.lowLabel, true, 'llm-value-ramp-side');
if (kind === 'diverging') {
var cy = at(0.5);
var cl = g.append('line').attr('class', 'llm-value-ramp-mid').attr('x1', 0).attr('x2', w)
.attr('y1', cy).attr('y2', cy).attr('stroke', fg).attr('stroke-opacity', 0.6).attr('stroke-width', 1);
if (!placeY(cy + 0.3 * fs, fmt(mid), false)) cl.append('title').text(fmt(mid));
}
(o.marks || []).forEach(function (m) {
var v = num(m && m.value);
if (v == null || atCentre(v)) return;
var y = at(frac(v));
var text = (m.label != null && m.label !== '' ? m.label + ' ' : '') + fmt(v);
var tick = g.append('line').attr('class', 'llm-value-ramp-mark').attr('x1', -2).attr('x2', w + 2)
.attr('y1', y).attr('y2', y).attr('stroke', fg).attr('stroke-width', 1.5).attr('stroke-dasharray', '3,2');
if (!placeY(y + 0.3 * fs, text, false)) tick.append('title').text(text);
});
if (kind === 'bands') for (var e = 1; e < k; e++) placeY(at(e / k) + 0.3 * fs, fmt(edges[e]), false);
return box();
};
var drawLegend = function (parent, o) {
o = o || {};
var vertical = o.orient === 'vertical' ||
(o.orient !== 'horizontal' && +o.width > 0 && +o.height > 2 * +o.width);
var w = o.width || (vertical ? 12 : 120), h = o.height || (vertical ? 120 : 8), fs = Math.max(TYPE_FLOOR, o.fontSize || TYPE_FLOOR);
var fg = o.fg || '#333', op = o.fgOpacity == null ? 1 : o.fgOpacity;
var ly = o.labelY == null ? h + fs : o.labelY;
var fmt = typeof o.format === 'function' ? o.format : function (v) { return String(v); };
var g = parent.append('g').attr('class', 'llm-value-ramp').attr('data-kind', kind)
.attr('transform', 'translate(' + (o.x || 0) + ',' + (o.y || 0) + ')');
if (vertical) {
g.attr('data-orient', 'vertical');
return drawVertical(g, w, h, fs, fg, op, fmt, o);
}
var label = function (x, anchor, text) {
g.append('text').attr('class', 'llm-value-ramp-label').attr('x', x).attr('y', ly)
.attr('text-anchor', anchor).attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
};
var taken = [];
var place = function (x, anchor, text, always) {
var wd = String(text).length * fs * 0.58;
var x0 = anchor === 'start' ? x : anchor === 'end' ? x - wd : x - wd / 2;
if (!always && taken.some(function (s) { return x0 < s[1] + 4 && x0 + wd > s[0] - 4; })) return false;
taken.push([x0, x0 + wd]);
label(x, anchor, text);
return true;
};
var k = colors.length, sw = w / k;
var a0 = kind === 'diverging' ? edges[0] : lo, a1 = kind === 'diverging' ? edges[edges.length - 1] : hi;
if (kind !== 'bands') {
var id = o.id || ('llmramp-' + Math.abs((w * 131 + h * 7) | 0) + (kind === 'diverging' ? '-d' : ''));
var lg = g.append('defs').append('linearGradient').attr('id', id);
lg.append('stop').attr('offset', '0%').attr('stop-color', low);
if (kind === 'diverging') lg.append('stop').attr('offset', '50%').attr('stop-color', midColor);
lg.append('stop').attr('offset', '100%').attr('stop-color', high);
var bar = g.append('rect').attr('class', 'llm-value-ramp-bar').attr('width', w).attr('height', h)
.attr('fill', 'url(#' + id + ')');
if (o.stroke) bar.attr('stroke', o.stroke).attr('stroke-width', 0.5);
if (kind === 'constant') {
label(0, 'start', fmt(lo) + (o.constantText || ''));
return { width: w, height: Math.max(h, ly) };
}
place(0, 'start', fmt(a0), true);
place(w, 'end', fmt(a1), true);
if (kind === 'diverging') {
var cl = g.append('line').attr('class', 'llm-value-ramp-mid').attr('x1', w / 2).attr('x2', w / 2)
.attr('y1', 0).attr('y2', h).attr('stroke', fg).attr('stroke-opacity', 0.6).attr('stroke-width', 1);
if (!place(w / 2, 'middle', fmt(mid), false)) cl.append('title').text(fmt(mid));
}
} else {
for (var b = 0; b < k; b++) {
var r = g.append('rect').attr('class', 'llm-value-ramp-band').attr('x', b * sw).attr('width', sw)
.attr('height', h).attr('fill', colors[b]).attr('data-from', edges[b]).attr('data-to', edges[b + 1]);
if (o.stroke) r.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
place(0, 'start', fmt(lo), true);
place(w, 'end', fmt(hi), true);
}
(o.marks || []).forEach(function (m) {
var v = num(m && m.value);
if (v == null || atCentre(v)) return;
var x;
if (kind === 'bands') {
var bi = Math.max(0, Math.min(k - 1, d3.bisectRight(edges, v) - 1));
var span = edges[bi + 1] - edges[bi];
x = (bi + (span > 0 ? Math.max(0, Math.min(1, (v - edges[bi]) / span)) : 0)) * sw;
} else {
x = Math.max(0, Math.min(w, (v - a0) / (a1 - a0) * w));
}
var text = (m.label != null && m.label !== '' ? m.label + ' ' : '') + fmt(v);
var tick = g.append('line').attr('class', 'llm-value-ramp-mark').attr('x1', x).attr('x2', x)
.attr('y1', -2).attr('y2', h + 2).attr('stroke', fg).attr('stroke-width', 1.5)
.attr('stroke-dasharray', '3,2');
if (!place(x, 'middle', text, false)) tick.append('title').text(text);
});
if (kind === 'bands') for (var e = 1; e < k; e++) place(e * sw, 'middle', fmt(edges[e]), false);
var bottom = ly;
if (o.lowLabel || o.highLabel) {
var sy = ly + fs + 2, lwd = o.lowLabel ? String(o.lowLabel).length * fs * 0.58 : 0;
var hwd = o.highLabel ? String(o.highLabel).length * fs * 0.58 : 0;
var side = function (x, anchor, text) {
g.append('text').attr('class', 'llm-value-ramp-side').attr('x', x).attr('y', sy)
.attr('text-anchor', anchor).attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
};
if (o.lowLabel) side(0, 'start', o.lowLabel);
if (o.highLabel) { if (lwd + hwd + 8 > w) side(lwd ? lwd + 8 : 0, 'start', o.highLabel); else side(w, 'end', o.highLabel); }
bottom = sy;
}
return { width: w, height: Math.max(h, bottom) };
};
var colorOf = function (v) { v = num(v); return v == null ? null : scale(v); };
var relLum = function (c) {
var q = c ? d3.color(c) : null;
if (!q) return null;
q = q.rgb();
var f = function (u) { u /= 255; return u <= 0.03928 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4); };
var L = 0.2126 * f(q.r) + 0.7152 * f(q.g) + 0.0722 * f(q.b);
return isFinite(L) ? L : null;
};
var ink = function (v, a, b) {
var lf = relLum(colorOf(v)), la = relLum(a), lb = relLum(b);
if (lf == null || la == null || lb == null) return a;
var ratio = function (x, y) { return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
return ratio(lf, la) >= ratio(lf, lb) ? a : b;
};
var self = {
color: colorOf, ink: ink,
kind: kind, skewed: kind === 'bands', lo: lo, hi: hi, median: median, p95: p95, mid: diverging ? mid : null,
edges: edges, colors: colors, drawLegend: drawLegend,
landFill: function (c) {
if (!darkCanvas) return c || '#e6e6e6';
return offPage(c || d3.lab(d3.lab(cvColor).l, 0, 0).formatHex(), 3);
},
onCanvas: function (o) {
var canvas = o, hc = false, next = null;
if (o && typeof o === 'object') {
canvas = o.backgroundColor && o.backgroundColor !== 'transparent' ? o.backgroundColor : o.themeBg;
hc = !!o.isHighContrast;
var scope = d3.llmFilterScope(o);
var kept = scope.domain('llmValueRamp:' + (cfg.key == null ? '' : String(cfg.key)), cfg.values || []);
if (scope.narrowed && kept.cohort === 'all') next = { values: kept.values };
}
if (canvas && !cfg.canvas) next = Object.assign(next || {}, { canvas: canvas, highContrast: hc });
return next ? d3.llmValueRamp(Object.assign({}, cfg, next)) : self;
},
};
return self;
};
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;
};
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.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;
}
};
};
// @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) {
const HEX_TILES = {
AK: [0, 0], ME: [10, 0],
VT: [9, 1], NH: [10, 1],
WA: [1, 2], ID: [2, 2], MT: [3, 2], ND: [4, 2], MN: [5, 2], WI: [6, 2], MI: [7, 2],
NY: [9, 2], RI: [10, 2], MA: [11, 2],
OR: [1, 3], NV: [2, 3], WY: [3, 3], SD: [4, 3], IA: [5, 3], IL: [6, 3], IN: [7, 3],
OH: [8, 3], PA: [9, 3], NJ: [10, 3], CT: [11, 3],
CA: [1, 4], UT: [2, 4], CO: [3, 4], NE: [4, 4], MO: [5, 4], KY: [6, 4], WV: [7, 4],
VA: [8, 4], MD: [9, 4], DE: [10, 4],
AZ: [2, 5], NM: [3, 5], KS: [4, 5], AR: [5, 5], TN: [6, 5], NC: [7, 5], SC: [8, 5], DC: [9, 5],
OK: [3, 6], LA: [4, 6], MS: [5, 6], AL: [6, 6], GA: [7, 6],
HI: [0, 7], TX: [3, 7], FL: [8, 7]
};
const TYPE_FLOOR = 10;
const { columns, rows } = data;
container.replaceChildren();
const W = options.width, H = options.height;
const CF = Math.max(TYPE_FLOOR, Math.min(14, Math.round(Math.min(W, H) / 34)));
const fg = options.themeFg || 'currentColor';
const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
const fmt = new Intl.NumberFormat(options.cultureCode || 'en-US', { maximumFractionDigits: 2 });
const ci = n => columns.findIndex(c => c.name === n);
const isoIdx = ci('__geoIso__'), idxIdx = ci('__rowIdx__');
if (isoIdx < 0) throw new Error('INVALID:column "__geoIso__" not found');
const ordIdx = ci('Sum of Orders'), rrIdx = ci('ReturnRate');
const V = d3.llmValueColumn(columns, rows, { countLabel: 'States', excludeCoordinates: true });
const labelIdx = V.labelIndex;
const aggM = (options.aggregation || '').toLowerCase();
const agg = a => !a.length ? null : aggM === 'average' ? d3.mean(a) : aggM === 'median' ? d3.median(a) : aggM === 'min' ? d3.min(a) : aggM === 'max' ? d3.max(a) : aggM === 'count' ? a.length : aggM === 'distinct' ? new Set(a).size : d3.sum(a);
const aggWord = { average: 'Average', median: 'Median', min: 'Min', max: 'Max', count: 'Count of', distinct: 'Distinct' }[aggM] || '';
const baseName = V.isCount ? V.valueName : d3.llmDisplayName(V.valueName);
const channel = V.isCount ? V.valueName + ' (count of rows)' : (aggWord ? aggWord + ' ' + baseName : baseName);
const byIso = new Map();
for (let r = 0; r < rows.length; r++) {
const row = rows[r], iso = row[isoIdx];
if (iso == null || iso === '') continue;
let g = byIso.get(iso);
if (!g) byIso.set(iso, g = { iso, label: labelIdx >= 0 ? row[labelIdx] : iso, vals: [], ord: [], rr: [], idx: [], value: null });
const mv = V.valueOf(row);
if (mv != null) g.vals.push(mv);
if (ordIdx >= 0 && row[ordIdx] != null && row[ordIdx] !== '' && isFinite(+row[ordIdx])) g.ord.push(+row[ordIdx]);
if (rrIdx >= 0 && row[rrIdx] != null && row[rrIdx] !== '' && isFinite(+row[rrIdx])) g.rr.push(+row[rrIdx]);
g.idx.push(idxIdx >= 0 ? row[idxIdx] : r);
}
if (byIso.size === 0) {
svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('fill', fg)
.attr('font-size', CF).text((typeof options.noDataText === 'string' && options.noDataText) ? options.noDataText : 'No data to display');
return;
}
byIso.forEach(g => { g.value = agg(g.vals); });
const EXTRA = [];
byIso.forEach((g, iso) => { if (!HEX_TILES[iso]) EXTRA.push(iso); });
EXTRA.sort();
const unm = options.geoUnmatched && options.geoUnmatched.count;
const LEGX = 8, LEGTY = 8 + CF, LEGY = LEGTY + 6, LEGW = Math.min(140, W * 0.34), LEGH = 8;
const legendBand = LEGY + LEGH + CF + 10;
const footBand = CF + 10;
let maxCol = 0, maxRow = 0;
for (const k in HEX_TILES) {
maxCol = Math.max(maxCol, HEX_TILES[k][0]);
maxRow = Math.max(maxRow, HEX_TILES[k][1]);
}
const TILES = Object.assign({}, HEX_TILES);
EXTRA.forEach((iso, k) => { TILES[iso] = [k % (maxCol + 1), maxRow + 1 + Math.floor(k / (maxCol + 1))]; });
if (EXTRA.length) maxRow += 1 + Math.floor((EXTRA.length - 1) / (maxCol + 1));
const cols = maxCol + 1, rowsN = maxRow + 1;
const availW = W - 12, availH = H - legendBand - footBand;
const s = Math.max(4, Math.min(availW / (Math.sqrt(3) * (cols + 0.5)), availH / (1.5 * rowsN + 0.5)));
const hexW = Math.sqrt(3) * s;
const gridW = hexW * (cols + 0.5), gridH = 1.5 * rowsN * s + 0.5 * s;
const ox = (W - gridW) / 2 + hexW / 2, oy = legendBand + (availH - gridH) / 2 + s;
const hexPath = (cx, cy) => {
const p = [];
for (let i = 0; i < 6; i++) {
const a = Math.PI / 180 * (60 * i - 90);
p.push((cx + s * Math.cos(a)).toFixed(2) + ',' + (cy + s * Math.sin(a)).toFixed(2));
}
return 'M' + p.join('L') + 'Z';
};
const vals = [];
byIso.forEach((g, iso) => { if (g.value != null && TILES[iso]) vals.push(g.value); });
const primary = (options.palette && options.palette.length && options.palette[0]) || '#3182bd';
const scaleLo = options.colorScaleLow || options.colorScaleAutoLow || '#eef3f8';
const scaleHi = options.colorScaleHigh || options.colorScaleAutoHigh || primary;
const ramp = d3.llmValueRamp({ values: vals, low: scaleLo, high: scaleHi }).onCanvas(options);
const color = ramp.color;
const land = ramp.landFill(options.geoLandColor);
const noData = options.geoNoDataColor ? ramp.landFill(options.geoNoDataColor) : land;
const hollow = ramp.kind === 'diverging';
const isEmpty = c => !c.g || c.g.value == null;
const cells = [];
for (const iso in TILES) {
const t = TILES[iso];
cells.push({ iso, cx: ox + hexW * (t[0] + (t[1] % 2 ? 0.5 : 0)), cy: oy + 1.5 * s * t[1], g: byIso.get(iso) || null });
}
const gGrid = svg.append('g');
const tip = (options.allowTooltips !== false && d3.llmTooltip) ? d3.llmTooltip(container) : null;
const bg = options.backgroundColor || options.themeBg || '#fff';
const marks = gGrid.selectAll('path.hex').data(cells, c => c.iso).join('path')
.attr('class', c => c.g ? 'hex d3-mark' : 'hex')
.attr('d', c => hexPath(c.cx, c.cy))
.attr('data-row-idx', c => c.g ? c.g.idx.join(',') : null)
.attr('data-cx', c => c.g ? Math.round(c.cx * 10) / 10 : null)
.attr('data-cy', c => c.g ? Math.round(c.cy * 10) / 10 : null)
.attr('fill', c => (hollow && isEmpty(c)) ? 'none' : (!c.g ? land : (c.g.value == null ? noData : color(c.g.value))))
.attr('stroke', hollow ? fg : bg)
.attr('stroke-opacity', hollow ? 0.3 : null)
.attr('stroke-dasharray', c => (hollow && isEmpty(c)) ? '2,2' : null)
.attr('stroke-width', Math.max(1, s * 0.06))
.style('cursor', c => c.g ? 'pointer' : null);
if (tip) {
marks.on('mouseover', (e, c) => {
if (!c.g) return;
let h = '<b>' + c.g.label + '</b><br/>' + channel + ': ' + (c.g.value == null ? 'no data' : fmt.format(c.g.value));
if (ordIdx >= 0) h += '<br/>' + (aggWord ? aggWord + ' ' : '') + 'Sum of Orders: ' + (c.g.ord.length ? fmt.format(agg(c.g.ord)) : 'no data');
if (rrIdx >= 0) h += '<br/>' + (aggWord ? aggWord + ' ' : 'Mean ') + 'ReturnRate: ' + (c.g.rr.length ? fmt.format(aggM && aggM !== 'sum' ? agg(c.g.rr) : d3.mean(c.g.rr)) : 'no data');
tip.show(h, e);
}).on('mousemove', e => tip.move(e)).on('mouseout', () => tip.hide());
}
const CODE_FS = s * 0.62;
const labels = gGrid.selectAll('text.hexcode').data(CODE_FS >= TYPE_FLOOR ? cells : [], c => c.iso).join('text')
.attr('class', 'hexcode')
.attr('x', c => c.cx).attr('y', c => c.cy)
.attr('text-anchor', 'middle').attr('dominant-baseline', 'central')
.attr('font-size', Math.max(TYPE_FLOOR, CODE_FS))
.attr('fill', c => (c.g && c.g.value != null)
? (hollow ? ramp.ink(c.g.value, fg, bg) : bg) : fg)
.attr('fill-opacity', c => (hollow && isEmpty(c)) ? 0.6 : 0.95)
.style('pointer-events', 'none')
.text(c => c.iso);
d3.llmFitLabel(labels, () => hexW * 0.82);
if (unm > 0) {
const unmText = d3.llmPlaceUnit(data).count(unm) + ' unmatched';
const unmT = svg.append('text').attr('x', 8).attr('y', H - 8).attr('font-size', CF).attr('fill', fg).text(unmText);
d3.llmFitLabel(unmT, W - 16, { pad: 0, text: unmText });
}
if (EXTRA.length > 0) {
const last = TILES[EXTRA[EXTRA.length - 1]];
const capX = ox + hexW * (last[0] + (last[1] % 2 ? 0.5 : 0)) + hexW * 0.75, capY = oy + 1.5 * s * last[1];
const cap = EXTRA.length === 1 ? 'no spot on this layout' : EXTRA.length + ' places with no spot on this layout';
const ct = svg.append('text').attr('class', 'lch-tile-fallback-note').attr('x', capX).attr('y', capY)
.attr('dominant-baseline', 'central').attr('font-size', CF).attr('fill', fg).text(cap);
d3.llmFitLabel(ct, () => Math.max(0, W - 8 - capX), { pad: 0, minWidth: 8, overflow: 'drop', shrinkTo: TYPE_FLOOR, text: cap });
}
ramp.drawLegend(svg, { x: LEGX, y: LEGY, width: LEGW, height: LEGH, labelY: LEGH + CF, fontSize: CF,
fg: fg, fgOpacity: 0.8, format: v => fmt.format(v), id: 'llmhex-' + Math.abs((W * 131 + H) | 0), constantText: ' - every state alike' });
const chT = svg.append('text').attr('x', LEGX).attr('y', LEGTY).attr('font-size', CF).attr('fill', fg).attr('fill-opacity', 0.75).text(channel);
d3.llmFitLabel(chT, W - LEGX - 8, { pad: 0, text: channel });
if (chT.text() !== channel) chT.append('title').text(channel);
const gridNote = 'Every state is one equal tile - area carries no meaning';
const noteX = LEGX + LEGW + 12;
const noteG = svg.append('g').attr('class', 'lch-caption');
const noteT = noteG.append('text').attr('x', noteX).attr('y', LEGY + LEGH)
.attr('font-size', CF).attr('fill', fg).attr('fill-opacity', 0.75);
for (const form of [gridNote, 'Equal tiles - area carries no meaning', 'Area carries no meaning']) {
d3.llmFitLabel(noteT, Math.max(0, W - 8 - noteX), { pad: 0, text: form, overflow: 'drop' });
if (noteT.text()) break;
}
if (noteT.text() && noteT.text() !== gridNote) noteG.append('title').text(gridNote);
}
Keep going
- What a US hex-tile cartogram is, and when to use one
- Bivariate USA Choropleth (by state) on the same data
- North America (Bubbles) on the same data
- USA Choropleth (by state) on the same data
- World (Bubbles) on the same data
- Parallel coordinates on the same data
- Apps, Ontologies and RegiaBI - Oh My! (and a pile of new visualizations)
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.