Retention by starting cohort
How many of each cohort are still here, period after period?
3,600 subscription customers, one row each, with channel, plan, region, monthly fee, start date and end date, as of Dec 31, 2024. About half have not left yet, so their end date is blank: a lifetime analysis has to count them as still watched rather than drop them or measure them to today. Partner customers stay about twice as long as Web customers; the small Marketplace channel looks better than Web but is too small to tell from chance; region makes no difference. Made for retention curves, cohort retention triangles and churn risk lists. Pair it with Customer Retention Activity for who has gone quiet.
Customer Retention: Who Stays and Who Leaves: 3600 rows, 9 columns. Download the CSV
| CustomerKey | CustomerName | Channel | Plan | Region | StartDate | EndDate | MonthlyFee | SnapshotDate |
|---|---|---|---|---|---|---|---|---|
| 1 | Delta Consulting | Partner | Basic | Americas | 2022-01-01 | 50.85 | 2024-12-31 | |
| 2 | Summit Works | Direct sales | Plus | Europe | 2022-01-02 | 2022-01-29 | 164.10 | 2024-12-31 |
| 3 | Delta Hospitality | Direct sales | Basic | Asia Pacific | 2022-01-02 | 2022-07-08 | 44.42 | 2024-12-31 |
| 4 | Orchard Ventures | Direct sales | Pro | Americas | 2022-01-02 | 2023-11-26 | 431.86 | 2024-12-31 |
| 5 | Falcon Wholesale | Direct sales | Plus | Europe | 2022-01-02 | 2022-03-04 | 151.38 | 2024-12-31 |
| 6 | Bright Energy | Web | Basic | Asia Pacific | 2022-01-04 | 2022-11-20 | 49.35 | 2024-12-31 |
| 7 | Zephyr Tools | Web | Basic | Asia Pacific | 2022-01-04 | 2022-07-25 | 42.42 | 2024-12-31 |
| 8 | Red Plumbing | Web | Plus | Americas | 2022-01-04 | 2022-10-09 | 137.75 | 2024-12-31 |
| 9 | Lantern Engineering | Partner | Basic | Asia Pacific | 2022-01-04 | 52.29 | 2024-12-31 | |
| 10 | Highland Brands | Partner | Pro | Middle East & Africa | 2022-01-04 | 472.23 | 2024-12-31 |

How to read it
Each row is the group that started in one period, and each column is how long since, so newer cohorts have shorter rows. Read across a row for one cohort's decline, and down a column to compare cohorts at the same age.
The chart's code (56 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) {}
};
// @requires llmText
d3.llmSurvival = function (data, cfg) {
cfg = cfg || {};
var DAY = 86400000, DPM = 30.4375, Z = 1.959963984540054;
var MIN_AT_RISK = cfg.minAtRisk > 0 ? cfg.minAtRisk : 10;
var MIN_GROUP = cfg.minGroup > 0 ? cfg.minGroup : 20;
var SMALL_COHORT = 10, MAX_GROUPS = 8;
var NOUN = cfg.noun || d3.llmText('d3.survival.customers', 'customers');
var NOUN_ONE = cfg.noun ? NOUN.replace(/s$/, '') : d3.llmText('d3.survival.customer', 'customer');
var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var columns = (data && data.columns) || [];
var rows = (data && data.rows) || [];
function colIndex(name) {
if (name === undefined || name === null || name === '') return -1;
for (var i = 0; i < columns.length; i++) {
var c = columns[i];
if ((c && (c.name === name || c.displayName === name || c.queryName === name)) || c === name) return i;
}
return -1;
}
function cellOf(row, idx, name) {
if (row == null) return undefined;
if (Array.isArray(row)) return idx >= 0 ? row[idx] : undefined;
return row[name];
}
function blank(v) { return v === null || v === undefined || (typeof v === 'string' && v.trim() === ''); }
function toDay(v) {
if (blank(v)) return null;
var t;
if (v instanceof Date) t = v.getTime();
else if (typeof v === 'number') t = v;
else {
var s = String(v).trim();
var m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?)?$/.exec(s);
t = m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : new Date(s).getTime();
}
return isFinite(t) ? Math.floor(t / DAY) : null;
}
function toNum(v) {
if (blank(v)) return null;
var n = typeof v === 'number' ? v : parseFloat(String(v).replace(/,/g, ''));
return isFinite(n) ? n : null;
}
function ymd(day) { var d = new Date(day * DAY); return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()]; }
function isoDay(day) { return day === null ? null : new Date(day * DAY).toISOString().slice(0, 10); }
function longDay(day) { var p = ymd(day), mon = typeof d3.utcFormat === 'function' ? d3.utcFormat('%b')(new Date(day * DAY)) : MONTHS[p[1]]; return mon + ' ' + p[2] + ', ' + p[0]; }
function edate(day, k) {
var p = ymd(day), y = p[0], m = p[1] + k;
y += Math.floor(m / 12); m = ((m % 12) + 12) % 12;
var last = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
return Math.floor(Date.UTC(y, m, Math.min(p[2], last)) / DAY);
}
function ord(a, b) { a = String(a); b = String(b); return a < b ? -1 : a > b ? 1 : 0; }
function median(xs) {
if (!xs.length) return null;
var s = xs.slice().sort(function (a, b) { return a - b; }), h = s.length >> 1;
return s.length % 2 ? s[h] : (s[h - 1] + s[h]) / 2;
}
var form = cfg.tenure ? 'tenure' : 'dates';
var ci = {
start: colIndex(cfg.start), end: colIndex(cfg.end), tenure: colIndex(cfg.tenure), event: colIndex(cfg.event),
id: colIndex(cfg.id), count: colIndex(cfg.count), value: colIndex(cfg.value), last: colIndex(cfg.lastActive),
asOf: colIndex(cfg.asOf), rowIdx: colIndex(cfg.rowIdx || '__rowIdx__')
};
var unitDays = form === 'dates';
var raw = [], asOfDay = null, asOfSource = null, maxSeen = null, lastById = {};
for (var r = 0; r < rows.length; r++) {
var row = rows[r];
if (row == null) continue;
var rid = ci.rowIdx >= 0 || !Array.isArray(row) ? cellOf(row, ci.rowIdx, cfg.rowIdx || '__rowIdx__') : undefined;
var rec = { row: blank(rid) ? r : (toNum(rid) !== null ? toNum(rid) : rid), pos: r };
rec.id = cfg.id ? cellOf(row, ci.id, cfg.id) : null;
rec.id = blank(rec.id) ? null : String(rec.id);
rec.w = cfg.count ? toNum(cellOf(row, ci.count, cfg.count)) : 1;
rec.value = cfg.value ? toNum(cellOf(row, ci.value, cfg.value)) : null;
rec.last = cfg.lastActive ? toDay(cellOf(row, ci.last, cfg.lastActive)) : null;
if (unitDays) {
rec.start = toDay(cellOf(row, ci.start, cfg.start));
rec.endRaw = toDay(cellOf(row, ci.end, cfg.end));
[rec.start, rec.endRaw, rec.last].forEach(function (d) { if (d !== null && (maxSeen === null || d > maxSeen)) maxSeen = d; });
} else {
rec.dur = toNum(cellOf(row, ci.tenure, cfg.tenure));
rec.evRaw = cellOf(row, ci.event, cfg.event);
}
rec.groups = {};
raw.push(rec);
}
var eventUnresolved = null;
if (!unitDays) {
var LEFT = { 'yes': 1, 'y': 1, 'true': 1, 'churned': 1, 'churn': 1, 'left': 1, 'lost': 1, 'cancelled': 1, 'canceled': 1,
'closed': 1, 'inactive': 1, 'terminated': 1, 'exited': 1, 'attrited': 1, 'gone': 1, 'former': 1, 'departed': 1 };
var vals = {};
raw.forEach(function (x) { if (!blank(x.evRaw)) vals[String(x.evRaw).trim().toLowerCase()] = x.evRaw; });
var keys0 = Object.keys(vals).sort(ord), leftKey = null;
if (cfg.eventValue !== undefined && cfg.eventValue !== null && cfg.eventValue !== '') leftKey = String(cfg.eventValue).trim().toLowerCase();
else if (raw.some(function (x) { return x.evRaw === true || x.evRaw === false; })) leftKey = 'true';
else if (keys0.length && keys0.every(function (k) { return k === '0' || k === '1'; })) leftKey = '1';
else {
var hits = keys0.filter(function (k) { return LEFT[k]; });
if (hits.length === 1 && keys0.length <= 2) leftKey = hits[0];
else eventUnresolved = d3.llmText('d3.survival.event_unresolved', 'Which value of {field} means a {noun} left? Rename the values (for example Yes / No) to draw the curve.', { field: cfg.event, noun: NOUN_ONE });
}
raw.forEach(function (x) { x.event = leftKey !== null && !blank(x.evRaw) && String(x.evRaw).trim().toLowerCase() === leftKey ? 1 : 0; });
if (eventUnresolved) raw.length = 0;
}
if (unitDays) {
if (cfg.asOf instanceof Date || (cfg.asOf && ci.asOf < 0 && toDay(cfg.asOf) !== null)) {
asOfDay = toDay(cfg.asOf); asOfSource = 'stated';
} else if (cfg.asOf && ci.asOf >= 0) {
for (var a = 0; a < rows.length; a++) {
var dv = toDay(cellOf(rows[a], ci.asOf, cfg.asOf));
if (dv !== null && (asOfDay === null || dv > asOfDay)) asOfDay = dv;
}
asOfSource = cfg.asOf;
}
if (asOfDay === null) { asOfDay = maxSeen; asOfSource = 'latest date'; }
}
raw.forEach(function (x) { if (x.id !== null && x.last !== null && (!(x.id in lastById) || x.last > lastById[x.id])) lastById[x.id] = x.last; });
var recs = [], excluded = 0, endAfterAsOf = 0, skipped = 0, duplicates = 0, seenIds = {};
raw.forEach(function (x) {
if (x.id !== null) { if (seenIds[x.id]) { duplicates++; return; } seenIds[x.id] = true; x.last = x.id in lastById ? lastById[x.id] : x.last; }
if (!(x.w > 0)) { skipped++; return; }
if (unitDays) {
if (x.start === null || asOfDay === null || x.start > asOfDay) { skipped++; return; }
if (x.endRaw !== null && x.endRaw < x.start) { excluded++; return; }
if (x.endRaw !== null && x.endRaw > asOfDay) { endAfterAsOf++; x.end = null; } else x.end = x.endRaw;
x.event = x.end === null ? 0 : 1;
x.dur = (x.end === null ? asOfDay : x.end) - x.start;
} else if (x.dur === null || x.dur < 0) { skipped++; return; }
recs.push(x);
});
recs.sort(function (p, q) { return p.dur - q.dur || ord(p.row, q.row) || p.pos - q.pos; });
function lgamma(x) {
var g = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
if (x < 0.5) return Math.log(Math.PI / Math.abs(Math.sin(Math.PI * x))) - lgamma(1 - x);
x -= 1;
var a = g[0], t = x + 7.5;
for (var i = 1; i < 9; i++) a += g[i] / (x + i);
return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);
}
function gammaQ(a, x) {
if (!(x > 0)) return 1;
var ln = -x + a * Math.log(x) - lgamma(a), i;
if (x < a + 1) {
var ap = a, sum = 1 / a, del = sum;
for (i = 0; i < 1000; i++) { ap += 1; del *= x / ap; sum += del; if (Math.abs(del) < Math.abs(sum) * 1e-17) break; }
return Math.max(0, 1 - sum * Math.exp(ln));
}
var FP = 1e-300, b = x + 1 - a, c = 1 / FP, d = 1 / b, h = d;
for (i = 1; i < 1000; i++) {
var an = -i * (i - a);
b += 2; d = an * d + b; if (Math.abs(d) < FP) d = FP;
c = b + an / c; if (Math.abs(c) < FP) c = FP;
d = 1 / d;
var dl = d * c; h *= dl;
if (Math.abs(dl - 1) < 1e-16) break;
}
return Math.exp(ln) * h;
}
function chiSquareP(x, df) { return gammaQ(df / 2, x / 2); }
function km(list) {
var n = 0, deps = 0;
list.forEach(function (x) { n += x.w; deps += x.w * x.event; });
var steps = [], s = 1, v = 0, atRisk = n, i = 0;
while (i < list.length) {
var t = list[i].dur, d = 0, gone = 0;
while (i < list.length && list[i].dur === t) { d += list[i].w * list[i].event; gone += list[i].w; i++; }
if (d > 0) {
s *= 1 - d / atRisk;
if (atRisk > d && s > 0) v += d / (atRisk * (atRisk - d));
var lo = null, hi = null;
if (s > 0 && s < 1) {
var se = Math.sqrt(v) / Math.abs(Math.log(s));
lo = Math.pow(s, Math.exp(Z * se)); hi = Math.pow(s, Math.exp(-Z * se));
}
steps.push({ t: t, nRisk: atRisk, d: d, S: s, lo: lo, hi: hi });
}
atRisk -= gone;
}
var cut = null;
steps.forEach(function (st) { if (st.nRisk >= MIN_AT_RISK) cut = st.t; });
var med = { t: null, lo: null, hi: null };
steps.forEach(function (st) {
if (cut === null || st.t > cut) return;
if (med.t === null && st.S <= 0.5) med.t = st.t;
if (med.lo === null && ((st.lo !== null && st.lo <= 0.5) || st.S === 0)) med.lo = st.t;
var h = st.hi !== null ? st.hi : (st.S === 0 ? 0 : 1);
if (med.hi === null && h <= 0.5) med.hi = st.t;
});
return { n: n, events: deps, censored: n - deps, steps: steps, cut: cut, median: med };
}
function stepAt(curve, t) {
var st = null;
for (var i = 0; i < curve.steps.length && curve.steps[i].t <= t; i++) st = curve.steps[i];
return st;
}
function sAt(curve, t) { var st = stepAt(curve, t); return st ? st.S : 1; }
function logrank(list, keys) {
var k = keys.length, idx = {};
keys.forEach(function (g, i) { idx[g] = i; });
var sub = list.filter(function (x) { return x.gkey in idx; });
var O = new Array(k).fill(0), E = new Array(k).fill(0), V = [];
for (var a = 0; a < k; a++) V.push(new Array(k).fill(0));
var nG = new Array(k).fill(0), deps = 0;
sub.forEach(function (x) { nG[idx[x.gkey]] += x.w; deps += x.w * x.event; });
if (!deps) return null;
var i = 0;
while (i < sub.length) {
var t = sub[i].dur, dG = new Array(k).fill(0), goneG = new Array(k).fill(0);
while (i < sub.length && sub[i].dur === t) { var g = idx[sub[i].gkey]; dG[g] += sub[i].w * sub[i].event; goneG[g] += sub[i].w; i++; }
var n = 0, d = 0;
for (var q = 0; q < k; q++) { n += nG[q]; d += dG[q]; }
if (d > 0 && n > 0) {
for (var p = 0; p < k; p++) {
O[p] += dG[p]; E[p] += d * nG[p] / n;
if (n > 1) for (var h = 0; h < k; h++) V[p][h] += d * (n - d) / (n - 1) * nG[p] / n * ((p === h ? 1 : 0) - nG[h] / n);
}
}
for (var z = 0; z < k; z++) nG[z] -= goneG[z];
}
var m = k - 1, A = [], U = [];
for (var r1 = 0; r1 < m; r1++) { A.push(V[r1].slice(0, m)); U.push(O[r1] - E[r1]); }
var x = U.slice();
for (var col = 0; col < m; col++) {
var piv = col;
for (var r2 = col + 1; r2 < m; r2++) if (Math.abs(A[r2][col]) > Math.abs(A[piv][col])) piv = r2;
var tmp = A[col]; A[col] = A[piv]; A[piv] = tmp; var tx = x[col]; x[col] = x[piv]; x[piv] = tx;
if (Math.abs(A[col][col]) < 1e-300) return null;
for (var r3 = col + 1; r3 < m; r3++) {
var f = A[r3][col] / A[col][col];
for (var c3 = col; c3 < m; c3++) A[r3][c3] -= f * A[col][c3];
x[r3] -= f * x[col];
}
}
for (var r4 = m - 1; r4 >= 0; r4--) {
var acc = x[r4];
for (var c4 = r4 + 1; c4 < m; c4++) acc -= A[r4][c4] * x[c4];
x[r4] = acc / A[r4][r4];
}
var chi2 = 0;
for (var r5 = 0; r5 < m; r5++) chi2 += U[r5] * x[r5];
return { chi2: chi2, df: m, p: chiSquareP(chi2, m) };
}
function monthsOf(t) { return unitDays ? t / DPM : t; }
function mo(t) { var v = Math.round(monthsOf(t)); return v === 1 ? d3.llmText('d3.survival.months', '{count} month', { count: v }, v) : d3.llmText('d3.survival.months', '{count} months', { count: v }, v); }
function pct(x) { return Math.round(x * 100) + '%'; }
var horizonUnit = unitDays ? 90 : 90 / DPM;
var maxDur = recs.reduce(function (mx, x) { return Math.max(mx, x.dur); }, 0);
var tickMonths = [0, 3, 6, 12, 18, 24, 36].filter(function (m) { return m * (unitDays ? DPM : 1) <= maxDur; });
for (var tm = 48; tm * (unitDays ? DPM : 1) <= maxDur; tm += 12) tickMonths.push(tm);
function atTicks(list) {
return tickMonths.map(function (m) {
var u = m * (unitDays ? DPM : 1), s = 0;
list.forEach(function (x) { if (x.dur >= u) s += x.w; });
return s;
});
}
function describe(list, key) {
var c = km(list), t12 = unitDays ? 365.25 : 12, st = stepAt(c, t12);
c.key = key;
c.s12 = { S: st ? st.S : 1, lo: st ? st.lo : null, hi: st ? st.hi : null };
c.rowIdx = list.map(function (x) { return x.row; });
c.atTicks = atTicks(list);
return c;
}
var all = describe(recs, null);
var fits = {}, lastField;
function fit(groupField) {
var field = groupField === undefined ? (cfg.group || (cfg.groups && cfg.groups[0]) || null) : groupField;
var gi = colIndex(field);
recs.forEach(function (x) {
var row = rows[x.pos], v = field ? cellOf(row, gi, field) : null;
x.gkey = blank(v) ? d3.llmText('d3.treemapanim.blank', '(blank)') : String(v);
});
lastField = field;
if (fits[field]) return fits[field];
var keys = [];
if (field) recs.forEach(function (x) { if (keys.indexOf(x.gkey) < 0) keys.push(x.gkey); });
keys.sort(ord);
var domain = (cfg.groupDomain && cfg.groupDomain[field]) ? cfg.groupDomain[field].map(String).slice().sort(ord) : keys;
var groups = keys.map(function (key) {
var g = describe(recs.filter(function (x) { return x.gkey === key; }), key);
g.drawn = g.n >= MIN_GROUP;
g.color = domain.indexOf(key) >= 0 ? domain.indexOf(key) : domain.length + keys.indexOf(key);
return g;
});
var drawn = groups.filter(function (g) { return g.drawn; });
var drawnKeys = drawn.map(function (g) { return g.key; });
var test = null, pairs = [];
if (drawnKeys.length >= 2) {
test = logrank(recs, drawnKeys);
if (test && drawnKeys.length >= 3 && test.p < 0.05) {
for (var i = 0; i < drawnKeys.length; i++) for (var j = i + 1; j < drawnKeys.length; j++) {
var lr = logrank(recs, [drawnKeys[i], drawnKeys[j]]);
if (lr) pairs.push({ a: drawnKeys[i], b: drawnKeys[j], key: drawnKeys[i] + '|' + drawnKeys[j], chi2: lr.chi2, p: lr.p });
}
var order = pairs.map(function (_, q) { return q; }).sort(function (p, q) { return pairs[p].p - pairs[q].p || ord(pairs[p].key, pairs[q].key); });
var running = 0;
order.forEach(function (q, rank) { running = Math.max(running, Math.min(1, (pairs.length - rank) * pairs[q].p)); pairs[q].pHolm = running; });
}
if (test) test.pairs = pairs;
}
var noun = field ? String(field).toLowerCase() : 'group';
var words = [], caption = [];
function half(g) {
return g.median.t !== null ? d3.llmText('d3.survival.half_gone', 'half are gone by {time}', { time: mo(g.median.t) }) : d3.llmText('d3.survival.half_stay', 'more than half are still with us after {time}', { time: mo(g.cut !== null ? g.cut : maxDur) });
}
function longer(a, b) { // positive when a keeps customers longer than b
var ta = a.median.t !== null ? a.median.t : Infinity, tb = b.median.t !== null ? b.median.t : Infinity;
if (ta !== tb) return ta > tb ? 1 : -1;
var t = Math.min(a.cut || 0, b.cut || 0);
return sAt(a, t) - sAt(b, t);
}
var byKey = {};
groups.forEach(function (g) { byKey[g.key] = g; });
if (eventUnresolved) words.push(eventUnresolved);
else if (recs.length && all.n < MIN_AT_RISK) words.push(d3.llmText('d3.survival.too_few', 'Too few {noun} in view for a curve ({count}).', { noun: NOUN, count: all.n }));
else if (!all.events) words.push(field && drawn.length === 1 ? d3.llmText('d3.survival.nobody_left_in', 'Nobody in {group} has left yet.', { group: drawn[0].key }) : d3.llmText('d3.survival.nobody_left', 'Nobody has left yet.'));
else if (field && drawn.length === 1) words.push(d3.llmText('d3.survival.one_group', 'One {field} in view - nothing to compare.', { field: noun }));
else if (test && drawnKeys.length === 2) {
var A = byKey[drawnKeys[0]], B = byKey[drawnKeys[1]];
if (longer(A, B) < 0) { var T = A; A = B; B = T; }
words.push(test.p < 0.05
? d3.llmText('d3.survival.stay_longer_half', '{a} {noun} stay longer than {b} {noun} ({half} against {other}).', { a: A.key, b: B.key, noun: NOUN, half: half(A), other: B.median.t !== null ? mo(B.median.t) : half(B) })
: d3.llmText('d3.survival.looks_better', '{a} looks better than {b}, but with {count} {noun} in the smaller group that gap could be chance.', { a: A.key, b: B.key, count: Math.min(A.n, B.n), noun: NOUN }));
} else if (test && drawnKeys.length >= 3) {
if (test.p >= 0.05) words.push(d3.llmText('d3.survival.all_same', 'The {field} curves could all be the same: the gaps between them could be chance.', { field: noun }));
else {
var chance = {}, chanceOrder = [];
pairs.slice().sort(function (p, q) { return p.pHolm - q.pHolm || ord(p.key, q.key); }).forEach(function (pr) {
var A2 = byKey[pr.a], B2 = byKey[pr.b];
if (longer(A2, B2) < 0) { var T2 = A2; A2 = B2; B2 = T2; }
if (pr.pHolm < 0.05) words.push(d3.llmText('d3.survival.stay_longer', '{a} {noun} stay longer than {b} {noun}.', { a: A2.key, b: B2.key, noun: NOUN }));
else if (A2.n < 100 || B2.n < 100) {
var small = A2.n <= B2.n ? A2 : B2, other = small === A2 ? B2 : A2;
if (!chance[small.key]) { chance[small.key] = []; chanceOrder.push(small); }
chance[small.key].push(other.key);
}
});
chanceOrder.forEach(function (g) {
var o = chance[g.key], list = o.length === 1 ? o[0] : d3.llmText('d3.segments.list_and', '{list} and {last}', { list: o.slice(0, -1).join(', '), last: o[o.length - 1] });
words.push(o.length === 1
? d3.llmText('d3.survival.gap_chance', "{group}'s gap to {list} could be chance: it has only {n} {noun}.", { group: g.key, list: list, n: g.n, noun: NOUN }, o.length)
: d3.llmText('d3.survival.gap_chance', "{group}'s gaps to {list} could be chance: it has only {n} {noun}.", { group: g.key, list: list, n: g.n, noun: NOUN }, o.length));
});
words.push(d3.llmText('d3.survival.pairs_compared', '{count} pairs were compared, so each had to clear a stricter bar.', { count: pairs.length }, pairs.length));
}
} else if (all.events) words.push(d3.llmText('d3.survival.of_all', 'Of all {noun}, {half}.', { noun: NOUN, half: half(all) }));
if (unitDays && asOfDay !== null) caption.push(asOfSource === 'latest date' ? d3.llmText('d3.survival.as_of_latest', 'As of {date} (the latest date in the data).', { date: longDay(asOfDay) }) : d3.llmText('d3.survival.as_of', 'As of {date}.', { date: longDay(asOfDay) }));
var stops = [];
groups.forEach(function (g) {
if (!g.drawn) caption.push(d3.llmText('d3.survival.too_few_alone', '{group} has {count} {noun}, too few to draw alone; they count in all {noun}.', { group: g.key, count: g.n, noun: NOUN }));
else if (g.cut !== null && g.steps.length && g.cut < maxDur) stops.push({ key: g.key, m: Math.round(monthsOf(g.cut)) });
});
if (stops.length) {
var at = stops.map(function (s) { return d3.llmText('d3.survival.stop_at', '{group} at {m}', { group: s.key, m: s.m }); });
var atList = at.length === 1 ? at[0] : d3.llmText('d3.segments.list_and', '{list} and {last}', { list: at.slice(0, -1).join(', '), last: at[at.length - 1] });
var lastM = stops[stops.length - 1].m;
caption.push(stops.length === 1
? (lastM === 1 ? d3.llmText('d3.survival.curve_stops', 'The curve stops where fewer than {min} {noun} were still watched: {at} month.', { min: MIN_AT_RISK, noun: NOUN, at: atList }, lastM)
: d3.llmText('d3.survival.curve_stops', 'The curve stops where fewer than {min} {noun} were still watched: {at} months.', { min: MIN_AT_RISK, noun: NOUN, at: atList }, lastM))
: (lastM === 1 ? d3.llmText('d3.survival.curves_stop', 'Curves stop where fewer than {min} {noun} were still watched: {at} month.', { min: MIN_AT_RISK, noun: NOUN, at: atList }, lastM)
: d3.llmText('d3.survival.curves_stop', 'Curves stop where fewer than {min} {noun} were still watched: {at} months.', { min: MIN_AT_RISK, noun: NOUN, at: atList }, lastM)));
}
if (groups.length > MAX_GROUPS) caption.push(d3.llmText('d3.survival.too_many_groups', '{field} has {count} values; at most {max} can be compared.', { field: field, count: groups.length, max: MAX_GROUPS }, groups.length));
if (excluded) caption.push(excluded === 1 ? d3.llmText('d3.survival.end_before_start', '{count} row ends before it starts - left out.', { count: excluded }, excluded) : d3.llmText('d3.survival.end_before_start', '{count} rows end before they start - left out.', { count: excluded }, excluded));
if (endAfterAsOf) caption.push(endAfterAsOf === 1 ? d3.llmText('d3.survival.end_after_as_of', '{count} end falls after the as-of date - counted as still with us then.', { count: endAfterAsOf }, endAfterAsOf) : d3.llmText('d3.survival.end_after_as_of', '{count} ends fall after the as-of date - counted as still with us then.', { count: endAfterAsOf }, endAfterAsOf));
if (duplicates) caption.push(d3.llmText('d3.survival.duplicates', '{noun} appear on several rows - counted once.', { noun: NOUN.charAt(0).toUpperCase() + NOUN.slice(1) }));
var res = {
field: field, asOf: isoDay(asOfDay), asOfSource: asOfSource, unit: unitDays ? 'days' : 'tenure', n: all.n,
active: recs.reduce(function (s, x) { return s + (x.event ? 0 : x.w); }, 0), excluded: excluded,
endAfterAsOf: endAfterAsOf, duplicates: duplicates, skipped: skipped, tickMonths: tickMonths,
groups: groups, drawn: drawnKeys, all: all, test: test, words: words, caption: caption
};
fits[field] = res;
return res;
}
function at(key, t, field) {
var F = fit(field !== undefined ? field : lastField), c = key === null || key === undefined ? all : null;
if (!c) F.groups.forEach(function (g) { if (g.key === String(key)) c = g; });
if (!c) return null;
var st = stepAt(c, t);
var nRisk = 0;
c.rowIdx && recs.forEach(function (x) { if ((c === all || x.gkey === c.key) && x.dur >= t) nRisk += x.w; });
return { S: st ? st.S : 1, lo: st ? st.lo : null, hi: st ? st.hi : null, nRisk: nRisk, past: c.cut !== null && t > c.cut };
}
function cohortKey(day, grain) {
var p = ymd(day);
if (grain === 'month') return p[0] + '-' + (p[1] < 9 ? '0' : '') + (p[1] + 1);
if (grain === 'quarter') return p[0] + ' Q' + (Math.floor(p[1] / 3) + 1);
return String(p[0]);
}
function cohortLast(key, grain) {
var y, m;
if (grain === 'month') { y = +key.slice(0, 4); m = +key.slice(5, 7) - 1; return Math.floor(Date.UTC(y, m + 1, 0) / DAY); }
if (grain === 'quarter') { y = +key.slice(0, 4); m = 3 * +key.slice(-1); return Math.floor(Date.UTC(y, m, 0) / DAY); }
return Math.floor(Date.UTC(+key, 12, 0) / DAY);
}
function cohorts(opts) {
if (!unitDays) return { ok: false, reason: d3.llmText('d3.survival.cohorts_need_start', 'A cohort triangle needs a start date; a tenure has no calendar.') };
var stated = (opts && opts.grain) || cfg.grain || null, sizesBy = {};
['month', 'quarter', 'year'].forEach(function (g) {
var s = {};
recs.forEach(function (x) { var k = cohortKey(x.start, g); s[k] = (s[k] || 0) + x.w; });
sizesBy[g] = s;
});
var grain = stated;
if (!grain) {
grain = 'year';
for (var gi2 = 0, gs = ['month', 'quarter', 'year']; gi2 < 3; gi2++) {
var vals = Object.keys(sizesBy[gs[gi2]]).map(function (k) { return sizesBy[gs[gi2]][k]; });
if (vals.length <= 24 && median(vals) >= 30) { grain = gs[gi2]; break; }
}
}
var sizes = sizesBy[grain], cols = [], k;
for (k = 1; k <= 36; k++) cols.push(k);
var foot = cols.map(function () { return [0, 0]; }), seen = 0, unseen = 0;
var out = Object.keys(sizes).sort(ord).map(function (key) {
var last = cohortLast(key, grain), members = recs.filter(function (x) { return cohortKey(x.start, grain) === key; });
var size = sizes[key], small = size < SMALL_COHORT;
var cells = cols.map(function (kk) {
if (edate(last, kk) > asOfDay) { unseen++; return { k: kk, seen: false, share: null }; }
seen++;
if (small) return { k: kk, seen: true, share: null };
var kept = 0;
members.forEach(function (x) { if (x.end === null || x.end > edate(x.start, kk)) kept += x.w; });
var share = kept / size;
foot[kk - 1][0] += share * size; foot[kk - 1][1] += size;
return { k: kk, seen: true, share: share, kept: kept };
});
return { cohort: key, size: size, small: small, lastDay: isoDay(last), rowIdx: members.map(function (x) { return x.row; }), cells: cells };
});
var caption = [d3.llmText('d3.survival.cohort_cell', "Each cell: the share of a {grain}'s new {noun} still with us that many months later. A hatched cell is not seen yet: not every {noun_one} in that {grain} could have been watched that long by {date}.", { grain: grain, noun: NOUN, noun_one: NOUN_ONE, date: longDay(asOfDay) }),
d3.llmText('d3.survival.cohort_bottom_row', 'The bottom row pools the cohorts watched that long, so a later month pools fewer of them.')];
if (out.some(function (r) { return r.small; }))
caption.push(d3.llmText('d3.survival.cohort_small', 'A plain row with no numbers: a {grain} with fewer than {min} new {noun}, too few for its shares to mean much.', { grain: grain, min: SMALL_COHORT, noun: NOUN }));
if (!stated) caption.push(d3.llmText('d3.survival.cohorts_by', 'Cohorts by {grain} ({count} rows).', { grain: grain, count: out.length }, out.length));
return {
ok: true, grain: grain, stated: stated, asOf: isoDay(asOfDay), columns: cols, rows: out, seen: seen, unseen: unseen,
footer: foot.map(function (f) { return f[1] ? f[0] / f[1] : null; }), caption: caption
};
}
function risk(opts) {
var H = opts && opts.horizonDays > 0 ? (unitDays ? opts.horizonDays : opts.horizonDays / DPM) : horizonUnit;
var F = fit(), byKey = {};
F.groups.forEach(function (g) { byKey[g.key] = g; });
var active = recs.filter(function (x) { return !x.event; });
var quietVals = [];
if (unitDays) active.forEach(function (x) { if (x.last !== null) quietVals.push(asOfDay - x.last); });
var med = median(quietVals), threshold = quietVals.length ? Math.max(21, 4 * med) : null;
var numeric = active.every(function (x) { return x.id !== null && isFinite(Number(x.id)); });
function rate(c, t) {
if (!c || c.cut === null || t + H > c.cut) return null;
var st = sAt(c, t);
return st <= 0 ? null : 1 - sAt(c, t + H) / st;
}
var hDays = unitDays ? Math.round(H) : (opts && opts.horizonDays > 0 ? opts.horizonDays : 90);
var hLabel = d3.llmText('d3.survival.horizon_days', '{count} days', { count: hDays }, hDays);
var shown = active;
if (opts && Array.isArray(opts.inView)) {
var keep = {};
opts.inView.forEach(function (p) { keep[p] = true; });
shown = active.filter(function (x) { return keep[x.pos]; });
}
var out = shown.map(function (x) {
var g = byKey[x.gkey], source = null, r = null;
if (g && g.drawn && g.cut !== null && x.dur + H <= g.cut) { source = 'group'; r = rate(g, x.dur); }
else if (all.cut !== null && x.dur + H <= all.cut) { source = 'all'; r = rate(all, x.dur); }
if (r === null) source = null;
var allR = rate(all, x.dur);
var quiet = unitDays && x.last !== null ? asOfDay - x.last : null;
var flagged = quiet !== null && threshold !== null && quiet > threshold;
var tm = Math.floor(unitDays ? x.dur / DPM : x.dur);
var why;
var tenure = tm === 1 ? d3.llmText('d3.survival.months', '{count} month', { count: tm }, tm) : d3.llmText('d3.survival.months', '{count} months', { count: tm }, tm);
if (r === null) why = d3.llmText('d3.survival.why_unrated', 'With us longer than anyone we can rate.');
else if (source === 'group') why = allR !== null
? d3.llmText('d3.survival.why_group_all', '{group} {noun} at {tenure} leave at {rate} within {horizon} (all {noun}: {all_rate})', { group: x.gkey, noun: NOUN, tenure: tenure, rate: pct(r), horizon: hLabel, all_rate: pct(allR) })
: d3.llmText('d3.survival.why_group', '{group} {noun} at {tenure} leave at {rate} within {horizon}', { group: x.gkey, noun: NOUN, tenure: tenure, rate: pct(r), horizon: hLabel });
else why = d3.llmText('d3.survival.why_all', '{noun} at {tenure} leave at {rate} within {horizon} (too few {group} {noun_lower} watched this long to rate alone)', { noun: NOUN.charAt(0).toUpperCase() + NOUN.slice(1), tenure: tenure, rate: pct(r), horizon: hLabel, group: x.gkey, noun_lower: NOUN });
if (r !== null && flagged) why += d3.llmText('d3.survival.why_quiet', ', quiet for {count} days (usually {usual})', { count: quiet, usual: Math.round(med) }, quiet);
if (r !== null) why += '.';
return {
__rowIdx__: x.row, id: x.id, group: x.gkey, tenure: x.dur, tenureMonths: tm, risk: r, source: source, allRisk: allR,
quietDays: quiet, quiet: flagged, value: x.value, expectedLoss: r !== null && x.value !== null ? r * x.value : null, why: why
};
});
out.sort(function (p, q) {
if ((p.risk === null) !== (q.risk === null)) return p.risk === null ? 1 : -1;
if (p.risk !== q.risk) return q.risk - p.risk;
if ((p.quietDays === null) !== (q.quietDays === null)) return p.quietDays === null ? 1 : -1;
if (p.quietDays !== q.quietDays) return q.quietDays - p.quietDays;
return numeric ? Number(p.id) - Number(q.id) : ord(p.id, q.id);
});
if (opts && opts.topN > 0) out = out.slice(0, opts.topN);
out.meta = { count: shown.length, quietThreshold: threshold, medianQuiet: med, flagged: out.filter(function (x) { return x.quiet; }).length, horizon: H,
ratedOn: all.n, activeAll: active.length, narrowed: shown !== active };
if (!shown.length) out.meta.message = shown !== active && active.length ? d3.llmText('d3.survival.none_picked', 'No {noun} the page picked is still with us.', { noun: NOUN_ONE })
: d3.llmText('d3.survival.all_left', 'Every {noun} in view has left.', { noun: NOUN_ONE });
return out;
}
return { fit: fit, at: at, cohorts: cohorts, risk: risk, chiSquareP: chiSquareP, form: form };
};
d3.llmTooltip = function (container, opts) {
opts = opts || {};
var gap = opts.gap == null ? 12 : opts.gap; // distance from the cursor
var edge = opts.edge == null ? 4 : opts.edge; // minimum distance from the container edge
var routed = false; // true while the HOST is showing our content
var lastContent = ''; // what to re-send if the host is driving
var lastEv = null; // where the cursor last was, for a re-fit
var host = (container && typeof container.node === 'function') ? container.node() : container;
var noop = { show: function () { return this; }, move: function () { return this; }, hide: function () { return this; },
html: function () { return this; }, text: function () { return this; }, node: null };
if (!host || !host.appendChild) return noop;
var mount = host;
if (mount.tagName && String(mount.tagName).toLowerCase() === 'svg' && mount.parentNode) {
mount = mount.parentNode;
}
if (!mount || !mount.appendChild) return noop;
try {
var pos = (typeof getComputedStyle === 'function') ? getComputedStyle(mount).position : '';
if (!pos || pos === 'static') mount.style.position = 'relative';
} catch (e) { /* jsdom / exec-gate: no layout engine, positioning is inert anyway */ }
var tip = mount.__llmTip;
if (!tip || tip.parentNode !== mount) {
tip = document.createElement('div');
tip.className = 'llm-tooltip';
tip.style.position = 'absolute';
tip.style.left = '0px';
tip.style.top = '0px';
tip.style.pointerEvents = 'none';
tip.style.visibility = 'hidden';
tip.style.zIndex = '20';
tip.style.boxSizing = 'border-box';
tip.style.whiteSpace = opts.wrap ? 'normal' : 'nowrap';
tip.style.background = 'rgba(255,255,255,0.97)';
tip.style.border = '1px solid rgba(0,0,0,0.28)';
tip.style.borderRadius = '4px';
tip.style.padding = '6px 9px';
tip.style.boxShadow = '0 2px 6px rgba(0,0,0,0.22)';
tip.style.color = '#222';
tip.style.fontSize = '12px';
mount.appendChild(tip);
mount.__llmTip = tip;
}
function hostTip() {
try {
var n = mount, guard = 0;
while (n && guard++ < 8) {
if (n.__lchHostTip && typeof n.__lchHostTip.show === 'function') return n.__lchHostTip;
n = n.parentNode;
}
} catch (e) { /* detached node / cross-document parent */ }
return null;
}
function metrics() {
var w = 0, h = 0, cw = 0, ch = 0;
try {
var r = mount.getBoundingClientRect();
cw = r.width; ch = r.height;
} catch (e) { /* fall through to the client* fallbacks */ }
if (!cw) cw = mount.clientWidth || 0;
if (!ch) ch = mount.clientHeight || 0;
w = tip.offsetWidth || 0;
h = tip.offsetHeight || 0;
return { w: w, h: h, cw: cw, ch: ch };
}
function local(ev) {
var x = 0, y = 0;
try {
var r = mount.getBoundingClientRect();
if (ev && ev.clientX != null) { x = ev.clientX - r.left; y = ev.clientY - r.top; }
} catch (e) {
if (ev && ev.clientX != null) { x = ev.clientX; y = ev.clientY; }
}
return { x: x, y: y };
}
function place(ev) {
var m = metrics();
if (!m.cw || !m.ch) return; // no layout to clamp against (exec gate)
var p = local(ev);
var left = p.x + gap;
if (left + m.w > m.cw - edge) left = p.x - gap - m.w;
if (left < edge) left = edge;
if (left + m.w > m.cw - edge) left = Math.max(edge, m.cw - m.w - edge);
var top = p.y + gap;
if (top + m.h > m.ch - edge) top = p.y - gap - m.h;
if (top < edge) top = edge;
if (top + m.h > m.ch - edge) top = Math.max(edge, m.ch - m.h - edge);
tip.style.left = Math.round(left) + 'px';
tip.style.top = Math.round(top) + 'px';
}
function looksLikeEvent(x) {
return !!x && typeof x === 'object' && !Array.isArray(x)
&& (typeof x.clientX === 'number' || typeof x.type === 'string' || ('target' in x));
}
function setContent(content, asText) {
if (Array.isArray(content)) content = content.map(function (x) { return x == null ? '' : String(x); }).join(asText ? ' ' : '<br/>');
lastContent = content == null ? '' : String(content);
if (!asText && typeof content === 'string' && content.indexOf('<') >= 0) tip.innerHTML = lastContent;
else tip.textContent = lastContent;
}
function setAndRefit(self, content, asText) {
setContent(content, asText);
if (routed) {
var hbSet = hostTip();
if (hbSet && hbSet.show(lastContent, lastEv) === true) return self;
routed = false; // the host let go: the tooltip is still on screen, so draw ours
return self.show(null, lastEv);
}
if (tip.style.visibility === 'visible') return self.show(null, lastEv);
return self;
}
return {
node: tip,
html: function (content) { return arguments.length ? setAndRefit(this, content, false) : lastContent; },
text: function (content) { return arguments.length ? setAndRefit(this, content, true) : (tip.textContent || ''); },
show: function (content, ev) {
if (looksLikeEvent(content) && !looksLikeEvent(ev)) { var swapped = content; content = ev; ev = swapped; }
if (ev) lastEv = ev;
if (content != null) setContent(content, false);
tip.style.maxWidth = 'none';
tip.style.visibility = 'visible'; // measurable BEFORE placing
var m = metrics();
if (m.ch && m.h + (2 * edge) > m.ch) {
var hbShow = hostTip();
if (hbShow && hbShow.show(lastContent, ev) === true) {
routed = true;
tip.style.visibility = 'hidden';
return this;
}
}
routed = false;
if (m.cw) tip.style.maxWidth = Math.max(80, m.cw - (2 * edge)) + 'px';
place(ev);
return this;
},
move: function (ev) {
if (ev) lastEv = ev;
if (routed) { var hbMove = hostTip(); if (hbMove) hbMove.move(ev); return this; }
if (tip.style.visibility === 'visible') place(ev);
return this;
},
hide: function () {
if (routed) { var hbHide = hostTip(); if (hbHide) hbHide.hide(); routed = false; }
tip.style.visibility = 'hidden';
return this;
}
};
};
d3.llmUtcDays = function (data, options) {
if (!data || !Array.isArray(data.columns) || !Array.isArray(data.rows)) return data;
if (options && options.dateCellsAreUtcDays === true) return data;
var DAY = 86400000;
var dateCols = [];
for (var ci = 0; ci < data.columns.length; ci++) {
var col = data.columns[ci];
if (col && /date|time/i.test(String(col.dataType || ''))) dateCols.push(ci);
}
if (!dateCols.length) return data;
function empty(v) { return v === null || v === undefined || v === ''; }
function localWall(t) { return t - new Date(t).getTimezoneOffset() * 60000; }
var fix = [];
for (var k = 0; k < dateCols.length; k++) {
var idx = dateCols[k], moved = 0, ok = true;
for (var r = 0; r < data.rows.length; r++) {
var row = data.rows[r];
if (!row || empty(row[idx])) continue;
var t = new Date(row[idx]).getTime();
if (!isFinite(t)) { ok = false; break; }
if (t % DAY === 0) continue;
if (localWall(t) % DAY !== 0) { ok = false; break; }
moved++;
}
if (ok && moved > 0) fix.push(idx);
}
if (!fix.length) return data;
var rows = data.rows.map(function (row) {
if (!row) return row;
var out = row.slice();
for (var f = 0; f < fix.length; f++) {
var j = fix[f];
if (empty(out[j])) continue;
var tt = new Date(out[j]).getTime();
if (tt % DAY === 0) continue;
out[j] = new Date(localWall(tt)).toISOString();
}
return out;
});
var result = {};
for (var key in data) if (Object.prototype.hasOwnProperty.call(data, key)) result[key] = data[key];
result.rows = rows;
return result;
};
d3.llmThemeColors = function (options) {
options = options || {};
var pick = function (v, d) { return (typeof v === 'string' && v && v !== 'transparent') ? v : d; };
var bg = pick(options.backgroundColor, pick(options.themeBg, '#ffffff'));
var fg = pick(options.themeFg, '#252423');
var hc = !!options.isHighContrast;
var pal = (options.palette && options.palette.length) ? options.palette.slice() : ['#4C78A8', '#F58518', '#54A24B', '#E45756', '#72B7B2', '#B279A2', '#FF9DA6', '#9D755D'];
var rgb = function (c) { var x = null; try { x = d3.rgb(c); } catch (e) { x = null; } return x && isFinite(x.r) ? x : d3.rgb(128, 128, 128); };
var lum = function (c) {
var r = rgb(c);
var f = function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r.r) + 0.7152 * f(r.g) + 0.0722 * f(r.b);
};
var contrast = function (a, b) { var x = lum(a) + 0.05, y = lum(b) + 0.05; return x > y ? x / y : y / x; };
var legible = function (col, floor) {
floor = floor || 3;
var c = d3.lab(rgb(col));
var step = lum(bg) > 0.5 ? -3 : 3; // a light background darkens the hue, a dark one lightens it
for (var i = 0; i < 34 && contrast(c.formatHex(), bg) < floor; i++) c.l = Math.max(0, Math.min(100, c.l + step));
return c.formatHex();
};
var good = hc ? pick(options.themeAccent, fg) : legible('#2e7d32');
var bad = hc ? fg : legible('#c62828');
var slot = function (value, n) {
var h = 2166136261, text = String(value);
for (var i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h % n;
};
var deltaE2000 = function (x, y) {
var rad = Math.PI / 180, L1 = x.l, a1 = x.a, b1 = x.b, L2 = y.l, a2 = y.a, b2 = y.b;
var C1 = Math.sqrt(a1 * a1 + b1 * b1), C2 = Math.sqrt(a2 * a2 + b2 * b2), Cm = (C1 + C2) / 2;
var G = 0.5 * (1 - Math.sqrt(Math.pow(Cm, 7) / (Math.pow(Cm, 7) + Math.pow(25, 7))));
var a1p = (1 + G) * a1, a2p = (1 + G) * a2;
var C1p = Math.sqrt(a1p * a1p + b1 * b1), C2p = Math.sqrt(a2p * a2p + b2 * b2);
var hp = function (bb, ap) { if (bb === 0 && ap === 0) return 0; var hh = Math.atan2(bb, ap) / rad; return hh < 0 ? hh + 360 : hh; };
var h1p = hp(b1, a1p), h2p = hp(b2, a2p);
var dLp = L2 - L1, dCp = C2p - C1p, dhp = 0;
if (C1p * C2p !== 0) { dhp = h2p - h1p; if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360; }
var dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhp * rad / 2);
var Lm = (L1 + L2) / 2, Cmp = (C1p + C2p) / 2, hm = h1p + h2p;
if (C1p * C2p !== 0) { if (Math.abs(h1p - h2p) > 180) hm += (hm < 360 ? 360 : -360); hm /= 2; }
var T = 1 - 0.17 * Math.cos((hm - 30) * rad) + 0.24 * Math.cos(2 * hm * rad) + 0.32 * Math.cos((3 * hm + 6) * rad) - 0.2 * Math.cos((4 * hm - 63) * rad);
var dTh = 30 * Math.exp(-Math.pow((hm - 275) / 25, 2));
var Rc = 2 * Math.sqrt(Math.pow(Cmp, 7) / (Math.pow(Cmp, 7) + Math.pow(25, 7)));
var Sl = 1 + 0.015 * Math.pow(Lm - 50, 2) / Math.sqrt(20 + Math.pow(Lm - 50, 2)), Sc = 1 + 0.045 * Cmp, Sh = 1 + 0.015 * Cmp * T;
var Rt = -Math.sin(2 * dTh * rad) * Rc;
var tl = dLp / Sl, tc = dCp / Sc, th = dHp / Sh;
return Math.sqrt(tl * tl + tc * tc + th * th + Rt * tc * th);
};
var order = null, pool = null, near = null;
var growOrder = function (count) {
if (!order) {
order = pal.map(function (c) { return rgb(c).formatHex(); });
var taken = order.map(function (c) { return d3.lab(c); });
var seenHex = {};
order.forEach(function (c) { seenHex[c] = 1; });
pool = [];
pal.forEach(function (c) {
var h = d3.hcl(rgb(c));
if (!isFinite(h.h)) h.h = 0;
var chroma = Math.max(isFinite(h.c) ? h.c : 0, 35);
[h.l, 38, 52, 66].forEach(function (L) {
for (var k = 1; k < 18; k++) {
var cc = d3.hcl((h.h + k * 20) % 360, chroma, L);
while (!cc.displayable() && cc.c > 20) cc.c -= 5;
if (!cc.displayable()) continue;
var hl = d3.hsl(cc).l;
if (!(hl > 0.15 && hl < 0.85)) continue;
var hx = cc.formatHex();
if (seenHex[hx]) continue;
seenHex[hx] = 1;
pool.push({ hex: hx, lab: d3.lab(hx) });
}
});
});
near = pool.map(function (q) {
var m = Infinity;
for (var t = 0; t < taken.length; t++) m = Math.min(m, deltaE2000(q.lab, taken[t]));
return m;
});
}
while (order.length < count && pool.length) {
var best = 0;
for (var q = 1; q < pool.length; q++) if (near[q] > near[best]) best = q;
var picked = pool.splice(best, 1)[0];
near.splice(best, 1);
order.push(picked.hex);
for (var r2 = 0; r2 < pool.length; r2++) near[r2] = Math.min(near[r2], deltaE2000(pool[r2].lab, picked.lab));
}
for (var round = 1; order.length < count && round < 40; round++) {
for (var e = 0; e < pal.length && order.length < count; e++) {
var hc = d3.hsl(pal[e]);
if (!isFinite(hc.h)) hc.h = 0;
var step = Math.ceil(round / 2) * 0.12 * (round % 2 ? 1 : -1);
hc.l = Math.max(0.12, Math.min(0.88, hc.l + step));
hc.h = (hc.h + round * 7) % 360;
var cx = hc.formatHex();
if (order.indexOf(cx) < 0) order.push(cx);
}
}
};
var extended = function (count) {
if (pal.length >= count) return pal.slice();
growOrder(count);
return pal.slice().concat(order.slice(pal.length, count));
};
var memory = function () {
var m = d3.__lchCategorySlots;
if (!m || !Array.isArray(m.groups)) { m = { groups: [] }; try { d3.__lchCategorySlots = m; } catch (e) { /* a frozen d3: no memory */ } }
return m;
};
var categories = function (values) {
var seen = {}, list = [];
(values || []).forEach(function (v) { var k = v === null || v === undefined ? '' : String(v); if (!seen[k]) { seen[k] = 1; list.push(k); } });
list.sort();
var mem = memory(), group = null, best = 0;
mem.groups.forEach(function (g) {
var shared = 0;
list.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(g.slots, k)) shared++; });
if (shared > best) { best = shared; group = g; }
});
if (!group) {
group = { slots: {}, used: {}, size: 0 };
mem.groups.push(group);
if (mem.groups.length > 32) mem.groups.shift();
}
var fresh = list.filter(function (k) { return !Object.prototype.hasOwnProperty.call(group.slots, k); });
var total = group.size + fresh.length;
var cols = extended(Math.max(list.length, total));
var n = cols.length;
fresh.forEach(function (k) {
if (group.size >= 2000) return; // a category this long is not a palette's job: past it, a value is placed but not remembered
var i = 0;
while (group.used[i] && i < n) i++;
group.used[i] = 1;
group.slots[k] = i;
group.size++;
});
var map = {};
list.forEach(function (k) {
var i = Object.prototype.hasOwnProperty.call(group.slots, k) ? group.slots[k] : slot(k, n);
if (i >= cols.length) cols = extended(i + 1);
map[k] = cols[i % cols.length];
});
return function (v) {
var k = v === null || v === undefined ? '' : String(v);
return map[k] || cols[slot(k, n)];
};
};
return { bg: bg, fg: fg, good: good, bad: bad, categories: categories, legible: function (c) { return legible(c); }, contrast: contrast, palette: pal };
};
function render(container, data, options) {
const TYPE_FLOOR = 10;
container.replaceChildren();
const START = 'StartDate', END = 'EndDate', AS_OF = 'SnapshotDate';
const W = options.width, H = options.height;
const FS = Math.max(TYPE_FLOOR, Math.min(13, Math.min(W, H) / 32));
const SUB_FS = Math.max(TYPE_FLOOR, FS * 0.9);
const fg = options.themeFg || 'currentColor';
const bg = options.themeBg || options.backgroundColor || '#fff';
const accent = options.colorScaleAutoHigh || options.themeAccent || ((options.palette && options.palette.length) ? options.palette[0] : '#4C78A8');
const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
const emptyFrame = function (msg) {
svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('font-size', FS).attr('fill', fg).text(msg);
};
const colNames = (data.columns || []).map(function (c) { return c.name; });
[START, END].forEach(function (n) {
if (colNames.indexOf(n) < 0) throw new Error('INVALID:column "' + n + '" not found');
});
const hasAsOf = colNames.indexOf(AS_OF) >= 0;
if (!data.rows || !data.rows.length) { emptyFrame(options.noDataText || 'No data to display'); return; }
data = d3.llmUtcDays(data, options);
const cfg = { start: START, end: END, asOf: hasAsOf ? AS_OF : undefined };
if (colNames.indexOf('Channel') >= 0) cfg.group = 'Channel';
if (colNames.indexOf('CustomerKey') >= 0) cfg.id = 'CustomerKey';
if (colNames.indexOf('MonthlyFee') >= 0) cfg.value = 'MonthlyFee';
const R = d3.llmSurvival(data, cfg);
const C = R.cohorts();
if (!C.ok) { emptyFrame(C.reason || options.noDataText || 'No data to display'); return; }
const T = d3.llmThemeColors(options);
const CULTURE = options.cultureCode || 'en-US';
const pctFmt = new Intl.NumberFormat(CULTURE, { style: 'percent', maximumFractionDigits: 0 });
const intFmt = new Intl.NumberFormat(CULTURE, { maximumFractionDigits: 0 });
const pct = function (v) { return pctFmt.format(v); };
const num = function (v) { return intFmt.format(v); };
const PAD = Math.round(FS * 0.6);
const labelW = Math.min(W * 0.3, FS * 0.6 * (d3.max(C.rows, function (r) { return (r.cohort + ' (' + r.size + ')').length; }) || 10) + PAD);
const plotW = W - 2 * PAD - labelW;
let cols = C.columns.slice(), picked = 'every month';
if (plotW / (cols.length + 2) < 22) {
const keep = W < 420 ? [1, 3, 6, 12, 24] : [1, 2, 3, 6, 9, 12, 18, 24, 30, 36];
cols = cols.filter(function (k) { return keep.indexOf(k) >= 0; });
picked = 'months ' + cols.join(', ');
}
function wrap(text, room, fs) {
const ws = String(text).split(/\s+/), lines = [];
let cur = '';
ws.forEach(function (w) {
const next = cur ? cur + ' ' + w : w;
if (!cur || next.length * fs * 0.56 <= room) cur = next; else { lines.push(cur); cur = w; }
});
if (cur) lines.push(cur);
return lines;
}
let capLines = [];
(C.caption || []).concat(picked === 'every month' ? [] : ['Showing ' + picked + '.']).forEach(function (c) {
capLines = capLines.concat(wrap(c, W - 2 * PAD, SUB_FS));
});
const CAP_H = capLines.length * SUB_FS * 1.3 + PAD;
const scaleLo = options.colorScaleLow || options.colorScaleAutoLow || d3.interpolateRgb(bg, accent)(0.15);
const scaleHi = options.colorScaleHigh || options.colorScaleAutoHigh || accent;
const ramp = d3.scaleLinear().domain([0, 1]).range([scaleLo, scaleHi]).interpolate(d3.interpolateLab).clamp(true);
const defs = svg.append('defs');
const hatchId = 'lch-hatch-' + Math.round(W) + '-' + Math.round(H);
const pat = defs.append('pattern').attr('id', hatchId).attr('patternUnits', 'userSpaceOnUse').attr('width', 6).attr('height', 6).attr('patternTransform', 'rotate(45)');
pat.append('rect').attr('width', 6).attr('height', 6).attr('fill', bg).attr('fill-opacity', 0.9);
pat.append('line').attr('x1', 0).attr('y1', 0).attr('x2', 0).attr('y2', 6).attr('stroke', fg).attr('stroke-opacity', 0.28).attr('stroke-width', 2);
let KEY_H = SUB_FS * 2;
const key = svg.append('g').attr('class', 'lch-cohort-key').attr('transform', 'translate(' + PAD + ',' + (PAD + SUB_FS) + ')');
const rampW = Math.min(160, W * 0.3);
const grad = defs.append('linearGradient').attr('id', hatchId + '-ramp');
d3.range(0, 1.0001, 0.25).forEach(function (t) {
grad.append('stop').attr('offset', (t * 100) + '%').attr('stop-color', ramp(t));
});
key.append('text').attr('font-size', SUB_FS).attr('fill', fg).attr('y', 0).text('Still with us');
const kx = SUB_FS * 0.56 * 13 + 24;
key.append('text').attr('x', kx).attr('font-size', SUB_FS).attr('fill', fg).attr('text-anchor', 'end').attr('dx', -4).text(pct(0));
key.append('rect').attr('x', kx).attr('y', -SUB_FS * 0.75).attr('width', rampW).attr('height', SUB_FS * 0.8).attr('fill', 'url(#' + hatchId + '-ramp)').attr('stroke', fg).attr('stroke-opacity', 0.25);
key.append('text').attr('x', kx + rampW + 4).attr('font-size', SUB_FS).attr('fill', fg).text(pct(1));
let ux = kx + rampW + SUB_FS * 3.4;
let uy = 0;
if (ux + SUB_FS * 8 > W - 2 * PAD) { ux = 0; uy = SUB_FS * 1.5; KEY_H += SUB_FS * 1.5; }
const unseenKey = key.append('g').attr('class', 'lch-cohort-unseen-key').attr('transform', 'translate(' + ux + ',' + uy + ')');
unseenKey.append('rect').attr('y', -SUB_FS * 0.75).attr('width', SUB_FS * 1.4).attr('height', SUB_FS * 0.8).attr('fill', 'url(#' + hatchId + ')').attr('stroke', fg).attr('stroke-opacity', 0.35);
unseenKey.append('text').attr('x', SUB_FS * 1.8).attr('font-size', SUB_FS).attr('fill', fg).text('not seen yet');
const top = PAD + KEY_H + SUB_FS * 2.9;
const nRows = C.rows.length + 1;
const cellW = plotW / cols.length;
const cellH = Math.max(TYPE_FLOOR + 4, Math.min(FS * 2.2, (H - top - CAP_H - PAD) / nRows));
const grid = svg.append('g').attr('class', 'lch-cohort').attr('transform', 'translate(' + (PAD + labelW) + ',' + top + ')');
const head = grid.append('g').attr('class', 'lch-cohort-head');
cols.forEach(function (k, ci) {
head.append('text').attr('x', (ci + 0.5) * cellW).attr('y', -SUB_FS * 0.45).attr('text-anchor', 'middle').attr('font-size', SUB_FS)
.attr('fill', fg).attr('fill-opacity', 0.75).text(cellW >= SUB_FS * 1.6 || k % 6 === 0 || k === 1 ? num(k) : '');
});
svg.append('text').attr('x', PAD).attr('y', top - SUB_FS * 0.45).attr('font-size', SUB_FS).attr('fill', fg).attr('fill-opacity', 0.75).text('Joined (customers)');
head.append('text').attr('x', 0).attr('y', -SUB_FS * 1.75).attr('font-size', SUB_FS).attr('fill', fg).attr('fill-opacity', 0.75).text('Months since joining \u2192');
const showNumbers = cellW >= SUB_FS * 2.4 && cellH >= SUB_FS * 1.3;
const tip = options.allowTooltips !== false ? d3.llmTooltip(container) : null;
const inkOn = function (fill) { return T.contrast(fill, fg) >= T.contrast(fill, '#fff') ? fg : '#fff'; };
const mo = function (k) { return num(k) + (k === 1 ? ' month' : ' months'); };
C.rows.forEach(function (r, ri) {
const y0 = ri * cellH, rowIdx = r.rowIdx.join(',');
const lab = svg.append('text').attr('class', 'lch-cohort-label d3-mark').attr('data-row-idx', rowIdx)
.attr('x', PAD).attr('y', top + y0 + cellH * 0.68).attr('font-size', SUB_FS).attr('fill', fg).style('cursor', 'pointer')
.attr('aria-label', r.cohort + ', ' + num(r.size) + ' new customers' + (r.small ? ', too few to show shares' : ''))
.text(r.cohort + ' (' + num(r.size) + ')');
if (r.small) lab.attr('fill-opacity', 0.6);
cols.forEach(function (k, ci) {
const cell = r.cells[k - 1], x0 = ci * cellW;
if (!cell) return;
if (!cell.seen) {
grid.append('rect').attr('class', 'lch-cohort-unseen').attr('x', x0 + 0.5).attr('y', y0 + 0.5).attr('width', cellW - 1).attr('height', cellH - 1)
.attr('fill', 'url(#' + hatchId + ')')
.on('mousemove', function (ev) { if (tip) tip.show('Joined in ' + r.cohort + ': not every customer could be watched ' + mo(k) + ' yet', ev); })
.on('mouseout', function () { if (tip) tip.hide(); });
return;
}
const noShare = r.small || cell.share === null || cell.share === undefined;
const fill = noShare ? d3.interpolateRgb(bg, fg)(0.12) : ramp(cell.share);
grid.append('rect').attr('class', 'lch-cohort-cell d3-mark').attr('data-row-idx', rowIdx)
.attr('x', x0 + 0.5).attr('y', y0 + 0.5).attr('width', cellW - 1).attr('height', cellH - 1).attr('fill', fill).style('cursor', 'pointer')
.attr('aria-label', r.cohort + ', ' + mo(k) + ' later: ' + (noShare ? 'too few customers to show a share' : pct(cell.share) + ' still with us'))
.on('mousemove', function (ev) { if (tip) tip.show('<b>' + r.cohort + '</b> (' + num(r.size) + ' customers)<br/>' + mo(k) + ' later: ' + (noShare ? 'too few to show a share' : pct(cell.share) + ' still with us'), ev); })
.on('mouseout', function () { if (tip) tip.hide(); });
if (showNumbers && !noShare)
grid.append('text').attr('class', 'lch-cohort-num').attr('x', x0 + cellW / 2).attr('y', y0 + cellH * 0.66).attr('text-anchor', 'middle')
.attr('font-size', Math.max(TYPE_FLOOR, Math.min(SUB_FS, cellW / 3))).attr('fill', inkOn(fill)).style('pointer-events', 'none').text(pct(cell.share));
});
});
const fy = C.rows.length * cellH + 2;
svg.append('text').attr('class', 'lch-cohort-foot-label').attr('x', PAD).attr('y', top + fy + cellH * 0.68).attr('font-size', SUB_FS)
.attr('font-weight', 600).attr('fill', fg).text('All cohorts');
cols.forEach(function (k, ci) {
const v = C.footer[k - 1];
if (v === null || v === undefined) return;
const fill = ramp(v);
grid.append('rect').attr('class', 'lch-cohort-foot').attr('x', ci * cellW + 0.5).attr('y', fy + 0.5).attr('width', cellW - 1).attr('height', cellH - 1)
.attr('fill', fill).attr('stroke', fg).attr('stroke-opacity', 0.35);
if (showNumbers) grid.append('text').attr('x', ci * cellW + cellW / 2).attr('y', fy + cellH * 0.66).attr('text-anchor', 'middle')
.attr('font-size', Math.max(TYPE_FLOOR, Math.min(SUB_FS, cellW / 3))).attr('font-weight', 600).attr('fill', inkOn(fill)).style('pointer-events', 'none').text(pct(v));
});
const capY = Math.min(H - CAP_H, top + fy + cellH + PAD * 1.5);
const cap = svg.append('g').attr('class', 'lch-cohort-caption');
capLines.forEach(function (l, i) {
cap.append('text').attr('x', PAD).attr('y', capY + (i + 0.85) * SUB_FS * 1.3).attr('font-size', SUB_FS).attr('fill', fg).attr('fill-opacity', 0.8).text(l);
});
}
Keep going
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.