How long customers stay, by Plan

Of the customers who start, how many are still here after each period, and does it differ by Plan?

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

The first 10 rows
CustomerKeyCustomerNameChannelPlanRegionStartDateEndDateMonthlyFeeSnapshotDate
1Delta ConsultingPartnerBasicAmericas2022-01-0150.852024-12-31
2Summit WorksDirect salesPlusEurope2022-01-022022-01-29164.102024-12-31
3Delta HospitalityDirect salesBasicAsia Pacific2022-01-022022-07-0844.422024-12-31
4Orchard VenturesDirect salesProAmericas2022-01-022023-11-26431.862024-12-31
5Falcon WholesaleDirect salesPlusEurope2022-01-022022-03-04151.382024-12-31
6Bright EnergyWebBasicAsia Pacific2022-01-042022-11-2049.352024-12-31
7Zephyr ToolsWebBasicAsia Pacific2022-01-042022-07-2542.422024-12-31
8Red PlumbingWebPlusAmericas2022-01-042022-10-09137.752024-12-31
9Lantern EngineeringPartnerBasicAsia Pacific2022-01-0452.292024-12-31
10Highland BrandsPartnerProMiddle East & Africa2022-01-04472.232024-12-31
Retention curves of the "Customer Retention: Who Stays and Who Leaves" dataset: 3,600 customers, starting with one curve for each of 3 Plan groups.
Retention curves of the "Customer Retention: Who Stays and Who Leaves" dataset: 3,600 customers, starting with one curve for each of 3 Plan groups.

How to read it

Each curve starts at everyone and steps down as customers leave, so a flatter curve keeps people longer; the shaded band is how sure the curve is. Switch what the curves compare by, and the curves, the plain-language comparisons above them and the counts of customers still being followed below regroup.

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

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

// bic:keyboard-marks
// English whatever the chart's language. A helper now asks for each one here and declares `// @requires llmText`:
d3.llmText = function (key, english, vars, count) {
var fill = function (s, vv) {
vv = vv || vars;
return String(s).replace(/\{([a-z][a-z0-9_]*)\}/g, function (m, k) {
return vv && Object.prototype.hasOwnProperty.call(vv, k) ? String(vv[k]) : m;
});
};
var en = fill(english);
var host = d3.llmText.host;
if (typeof host === 'function') {
try { var h = host(key, english, vars, count); if (typeof h === 'string' && h !== en && h !== english) return h; } catch (e) {}
}
var cat = d3.llmText._cat, lang = d3.llmText._lang;
if (cat && lang && Object.prototype.hasOwnProperty.call(cat, key)) {
var v = cat[key];
if (v && typeof v === 'object') {
var form = 'other';
try { form = new Intl.PluralRules(lang).select(typeof count === 'number' ? count : 0); } catch (e) {}
v = v[form] != null ? v[form] : v.other != null ? v.other : v.many;
}
var tv = vars;
if (vars && typeof vars.grain === 'string' && Object.prototype.hasOwnProperty.call(cat, 'd3.grain.' + vars.grain)
&& typeof cat['d3.grain.' + vars.grain] === 'string' && cat['d3.grain.' + vars.grain]) {
tv = {};
for (var vk in vars) if (Object.prototype.hasOwnProperty.call(vars, vk)) tv[vk] = vars[vk];
tv.grain = cat['d3.grain.' + vars.grain];
}
if (typeof v === 'string' && v) {
var t = fill(v, tv), left = String(t).match(/\{[a-z][a-z0-9_]*\}/g) || [];
if (left.every(function (x) { return en.indexOf(x) >= 0; })) return t;
}
}
return en;
};
d3.llmText._lang = null;
d3.llmText._cat = null;
d3.llmText.use = function (lang, catalog) {
d3.llmText._lang = lang || null; d3.llmText._cat = catalog || null;
d3.llmText.dates(lang);
};
d3.llmText.dates = function (lang) {
try {
var o = d3.llmText._d3orig;
if (!o) {
o = d3.llmText._d3orig = { timeFormat: d3.timeFormat, utcFormat: d3.utcFormat, timeParse: d3.timeParse,
utcParse: d3.utcParse, scaleTime: d3.scaleTime, scaleUtc: d3.scaleUtc };
}
var restore = function () { for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k) && o[k]) d3[k] = o[k]; };
var base = String(lang || '').toLowerCase().split(/[-_]/)[0];
if (!base || base === 'en' || typeof d3.timeFormatLocale !== 'function' || typeof Intl === 'undefined') { restore(); return; }
var mk = function (opts) { var x = { timeZone: 'UTC' }; for (var k in opts) x[k] = opts[k]; return new Intl.DateTimeFormat(lang, x); };
var months = [], shortMonths = [], days = [], shortDays = [], m, w;
var fM = mk({ month: 'long' }), fMs = mk({ month: 'short' }), fD = mk({ weekday: 'long' }), fDs = mk({ weekday: 'short' });
for (m = 0; m < 12; m++) { var dm = new Date(Date.UTC(2021, m, 15)); months.push(fM.format(dm)); shortMonths.push(fMs.format(dm)); }
for (w = 0; w < 7; w++) { var dw = new Date(Date.UTC(2021, 0, 3 + w)); days.push(fD.format(dw)); shortDays.push(fDs.format(dw)); }   // 3 Jan 2021 is a Sunday
if (months[0] === 'January' && days[0] === 'Sunday') { restore(); return; }   // no names for the language here: keep d3's
var L = d3.timeFormatLocale({ dateTime: '%x %X', date: '%Y-%m-%d', time: '%H:%M:%S', periods: ['AM', 'PM'],
days: days, shortDays: shortDays, months: months, shortMonths: shortMonths });
d3.timeFormat = L.format; d3.utcFormat = L.utcFormat; d3.timeParse = L.parse; d3.utcParse = L.utcParse;
var multi = function (utc) {
var F = utc ? L.utcFormat : L.format, P = utc ? 'utc' : 'time';
var iv = function (n) { return d3[P + n]; };
var fL = F('.%L'), fS = F(':%S'), fMi = F('%H:%M'), fH = F('%H:00'), fDy = F('%a %d'), fW = F('%b %d'), fMo = F('%B'), fY = F('%Y');
var wk = utc ? d3.utcSunday : d3.timeSunday;
return function (date) {
return (iv('Second')(date) < date ? fL : iv('Minute')(date) < date ? fS : iv('Hour')(date) < date ? fMi
: iv('Day')(date) < date ? fH : iv('Month')(date) < date ? (wk(date) < date ? fDy : fW)
: iv('Year')(date) < date ? fMo : fY)(date);
};
};
var wrap = function (make, utc) {
if (typeof make !== 'function') return make;
var dress = function (sc) {
var cp = sc.copy;
sc.tickFormat = function (count, spec) { return spec == null ? multi(utc) : (utc ? L.utcFormat : L.format)(spec); };
if (typeof cp === 'function') sc.copy = function () { return dress(cp.apply(sc, arguments)); };
return sc;
};
return function () { return dress(make.apply(this, arguments)); };
};
d3.scaleTime = wrap(o.scaleTime, false); d3.scaleUtc = wrap(o.scaleUtc, true);
} catch (e) {}
};
d3.llmSegmented = function (svg, cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px
cfg = cfg || {};
var options = cfg.options || {}, container = cfg.container;
var key = typeof cfg.key === 'string' && cfg.key ? cfg.key : 'segment';
var onChange = typeof cfg.onChange === 'function' ? cfg.onChange : function () {};
var offered = Array.isArray(cfg.choices) ? cfg.choices : [];
var choices = offered.map(d3.llmSegmented.choice).filter(function (c) {
return c && typeof c.value === 'string' && c.value !== '';
});
var noop = { value: function () { return null; }, set: function () {}, g: null,
bounds: function () { return { left: 0, right: 0, width: 0, height: 0 }; } };
if (!svg || choices.length < 2) {
if (svg && offered.length >= 2 && typeof svg.attr === 'function') {
var inert = svg.attr('data-llm-inert-control');
svg.attr('data-llm-inert-control', (inert ? inert + ',' : '') + key);
}
return noop;
}
var fg = options.themeFg || '#252423', accent = options.themeAccent || fg;
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var geo = d3.llmSegmented.measure({ choices: choices, fontSize: fsz, label: cfg.label });
var x = cfg.x != null ? +cfg.x : 0, y = cfg.y != null ? +cfg.y : 0;

function isChoice(v) {
if (typeof v !== 'string') return false;
for (var i = 0; i < choices.length; i++) if (choices[i].value === v) return true;
return false;
}
var fallback = isChoice(cfg['default']) ? cfg['default'] : choices[0].value;

var bag = {};
if (container) {
if (!container.__lchSegments || typeof container.__lchSegments !== 'object') container.__lchSegments = {};
bag = container.__lchSegments;
}
var ui = options.uiState && typeof options.uiState === 'object' ? options.uiState : {};
var restoredBag = ui.segments && typeof ui.segments === 'object' ? ui.segments : null;
var restored = restoredBag && Object.prototype.hasOwnProperty.call(restoredBag, key) ? restoredBag[key] : undefined;
var cur = isChoice(restored) ? restored : fallback;
var shown = bag && Object.prototype.hasOwnProperty.call(bag, key) ? bag[key] : undefined;
var codeChange = isChoice(restored) && shown !== undefined && restored !== shown;

var g = svg.append('g').attr('class', 'llm-segmented').attr('data-segment-key', key);
var maxW = +cfg.maxWidth > 0 ? +cfg.maxWidth : (+options.width > 0 ? +options.width - x - 4 : Infinity);
var lay = d3.llmSegmented.layout(geo, maxW);
var left = x;
if (cfg.label) {
g.append('text').attr('class', 'llm-segmented-label')
.attr('x', left).attr('y', y + fsz * 0.35).attr('font-size', Math.max(TYPE_FLOOR, fsz * 0.9))
.attr('fill', fg).attr('fill-opacity', 0.75).text(String(cfg.label));
left += geo.labelW;
}
var buttons = [];
choices.forEach(function (c, i) {
var w = geo.buttonW[i], rowY = y + lay.row[i] * (geo.height + 2);
left = x + lay.left[i];
var b = g.append('g').attr('class', 'llm-segmented-button lch-control').attr('data-segment-value', c.value)
.attr('cursor', 'pointer').attr('role', 'button')
.attr('aria-label', (cfg.label ? String(cfg.label) + ': ' : '') + String(c.label == null ? c.value : c.label));
b.append('rect').attr('class', 'llm-segmented-hit')
.attr('x', left).attr('y', rowY - geo.height / 2).attr('width', w).attr('height', geo.height)
.attr('rx', i === 0 || i === choices.length - 1 ? 3 : 0)
.attr('stroke', fg).attr('stroke-opacity', 0.35);
b.append('text').attr('class', 'llm-segmented-text')
.attr('x', left + w / 2).attr('y', rowY + fsz * 0.35).attr('text-anchor', 'middle')
.attr('font-size', fsz).text(String(c.label == null ? c.value : c.label));
b.on('click', function (event) {
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
setCur(c.value, 'click');
});
buttons.push({ value: c.value, g: b });
left += w;
});

function paint() {
buttons.forEach(function (bt) {
var on = bt.value === cur;
bt.g.attr('aria-pressed', on ? 'true' : 'false');
bt.g.select('rect').attr('fill', on ? accent : 'transparent').attr('fill-opacity', on ? 0.18 : 0);
bt.g.select('text').attr('fill', fg).attr('font-weight', on ? 'bold' : 'normal');
});
}
function persist() {
bag[key] = cur;
if (typeof options.setUiState !== 'function') return;
var live = container && container.__lchUiLiveOpts === options && container.__lchUiLiveSeed === options.uiState
? container.__lchUiLive : null;
var base = live || ui;
var next = {}, k;
for (k in base) if (Object.prototype.hasOwnProperty.call(base, k)) next[k] = base[k];
next.segments = {};
for (k in bag) if (Object.prototype.hasOwnProperty.call(bag, k)) next.segments[k] = bag[k];
if (container) { container.__lchUiLive = next; container.__lchUiLiveOpts = options; container.__lchUiLiveSeed = options.uiState; }
try { options.setUiState(next); } catch (e) { /* persistence is advisory, never fatal */ }
}
function report() {
if (!options || typeof options.onControlChange !== 'function') return;
try { options.onControlChange({ control: 'segmented', key: key, value: cur }); }
catch (e) { /* telemetry is advisory, never fatal */ }
}
function setCur(v, phase) {
if (!isChoice(v)) return;
if (v === cur && phase !== 'init') return;         // re-clicking the active button does nothing
cur = v;
paint();
if (phase === 'click') { persist(); report(); }
onChange(cur, phase);
}

paint();
bag[key] = cur;
if (codeChange) persist();
onChange(cur, 'init');
return {
value: function () { return cur; },
g: g,
set: function (v, fire) { setCur(v, fire === false ? 'init' : 'click'); },
bounds: function () { return { left: x, right: x + lay.width, width: lay.width, height: lay.height }; }
};
};
d3.llmSegmented.measure = function (cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px - the row draws no smaller, so it reserves no smaller
cfg = cfg || {};
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize : 11);
var choices = (Array.isArray(cfg.choices) ? cfg.choices : []).map(d3.llmSegmented.choice);
var pad = fsz * 0.9;
var buttonW = choices.map(function (c) {
var t = String(c && (c.label == null ? c.value : c.label));
return Math.max(20, Math.round(t.length * fsz * 0.6 + pad * 2));
});
var labelW = cfg.label ? Math.round(String(cfg.label).length * Math.max(TYPE_FLOOR, fsz * 0.9) * 0.6 + fsz * 0.6) : 0;
var width = labelW + buttonW.reduce(function (a, b) { return a + b; }, 0);
var geo = { width: width, height: Math.max(20, Math.round(fsz * 1.9)), buttonW: buttonW, labelW: labelW };
if (!(+cfg.maxWidth > 0)) return geo;
var lay = d3.llmSegmented.layout(geo, +cfg.maxWidth);
return { width: lay.width, height: lay.height, buttonW: buttonW, labelW: labelW, rows: lay.rows };
};
d3.llmSegmented.layout = function (geo, maxW) {
var start = geo.labelW, left = start, row = 0, lefts = [], rows = [], right = start;
for (var i = 0; i < geo.buttonW.length; i++) {
var w = geo.buttonW[i];
if (left + w > maxW && left > start) { row++; left = start; }
lefts.push(left); rows.push(row); left += w; if (left > right) right = left;
}
var n = row + 1;
return { left: lefts, row: rows, width: right, height: n * geo.height + (n - 1) * 2, rows: n };
};
d3.llmSegmented.choice = function (c) { return typeof c === 'string' ? { value: c, label: c } : c; };
// @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();
  var START = 'StartDate', END = 'EndDate', GROUPS = ['Channel', 'Plan', 'Region'], AS_OF = 'SnapshotDate', ID = 'CustomerKey', VALUE = 'MonthlyFee';
  var DEFAULT_GROUP = 'Plan';
  var W = options.width, H = options.height;
  var FS = Math.max(TYPE_FLOOR, Math.min(13, Math.min(W, H) / 32));
  var SUB_FS = Math.max(TYPE_FLOOR, FS * 0.9);
  var fg = options.themeFg || 'currentColor';
  var accent = options.themeAccent || '#4C78A8';
  var svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  var 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'); });
  GROUPS = GROUPS.filter(function (g) { return colNames.indexOf(g) >= 0; });
  var cfgId = colNames.indexOf(ID) >= 0 ? ID : undefined;
  var cfgVal = colNames.indexOf(VALUE) >= 0 ? VALUE : undefined;
  var cfgAsOf = colNames.indexOf(AS_OF) >= 0 ? AS_OF : undefined;
  data = d3.llmUtcDays(data, options);
  var rows = data.rows || [];
  if (!rows.length) {
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('font-size', FS).attr('fill', fg).text(options.noDataText || 'No data to display');
    return;
  }
  var CULTURE = options.cultureCode || 'en-US';
  var pctFmt = new Intl.NumberFormat(CULTURE, { style: 'percent', maximumFractionDigits: 0 });
  var intFmt = new Intl.NumberFormat(CULTURE, { maximumFractionDigits: 0 });
  var oneFmt = new Intl.NumberFormat(CULTURE, { maximumFractionDigits: 1 });
  function pct(v) { return pctFmt.format(v); }
  function num(v) { return intFmt.format(v); }
  var PAD = Math.round(FS * 0.6);
  var STRIP = GROUPS.length >= 2 ? Math.max(24, SUB_FS * 2.2) : 0;
  function words(n) { return String(n).replace(/[_-]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2'); }
  var field = GROUPS.indexOf(DEFAULT_GROUP) >= 0 ? DEFAULT_GROUP : (GROUPS[0] || null);
  if (STRIP) {
    var knobs = svg.append('g').attr('class', 'lch-knobs');
    var seg = d3.llmSegmented(svg, { container: container, options: options, key: 'compare', 'default': field, fontSize: SUB_FS, x: PAD, y: PAD + STRIP / 2,
      label: 'Compare by', choices: GROUPS.map(function (g) { return { value: g, label: words(g) }; }),
      onChange: function (v, phase) { if (phase === 'click') render(container, data, options); } });
    knobs.node().appendChild(seg.g.node());
    if (GROUPS.indexOf(seg.value()) >= 0) field = seg.value();
  }
  var R = d3.llmSurvival(data, { start: START, end: END, groups: GROUPS, group: GROUPS[0], id: cfgId, value: cfgVal, asOf: cfgAsOf });
  var F = R.fit(field);
  var DPM = 30.4375;
  var toMonths = function (t) { return t / DPM; };
  var drawnGroups = F.groups.filter(function (g) { return g.drawn; });
  var curves = drawnGroups.length ? drawnGroups : (F.all && F.all.steps ? [Object.assign({}, F.all, { key: 'All customers' })] : []);
  var T = d3.llmThemeColors(options);
  var colourOf = T.categories(F.groups.map(function (g) { return g.key; }));
  var colour = function (g) { return drawnGroups.length ? T.legible(colourOf(g.key)) : accent; };

  function wrap(text, room, fs, maxLines) {
    var ws = String(text).split(/\s+/), lines = [], cur = '';
    ws.forEach(function (w) { var 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;
  }
  function block(g, lines, x0, y0, fs, cls, dim) {
    lines.forEach(function (l, i) {
      g.append('text').attr('class', cls).attr('x', x0).attr('y', y0 + (i + 0.85) * fs * 1.3).attr('font-size', Math.max(TYPE_FLOOR, fs))
        .attr('fill', fg).attr('fill-opacity', dim ? 0.7 : 0.92).text(l);
    });
    return lines.length * fs * 1.3;
  }
  var top = PAD + STRIP;
  var MIN_PLOT = H * 0.4;
  var showRisk = H >= 380 && drawnGroups.length > 0 && drawnGroups.length <= 4;
  var riskH = function () { return showRisk ? (drawnGroups.length + 1) * SUB_FS * 1.25 + PAD : 0; };
  var LEG_ROW = SUB_FS * 1.6;
  var SHORT_LEGEND = false;
  function legendLabel(g) {
    var m = g.median && g.median.t !== null ? oneFmt.format(toMonths(g.median.t)) : null;
    var past = oneFmt.format(toMonths(g.cut !== null ? g.cut : g.steps[g.steps.length - 1].t));
    var med = m !== null ? 'median ' + m + ' mo' : 'median past ' + past + ' mo';
    return SHORT_LEGEND ? g.key + ': ' + med : g.key + ' (' + num(g.n) + ', ' + med + ')';
  }
  function legendW(g) { return SUB_FS * 1.4 + legendLabel(g).length * SUB_FS * 0.56 + PAD * 2; }
  function legendRows() {
    if (!drawnGroups.length) return 0;
    var lxs = PAD, n = 1;
    drawnGroups.forEach(function (g) { var w = legendW(g); if (lxs > PAD && lxs + w > W - PAD) { lxs = PAD; n++; } lxs += w; });
    return n;
  }
  var legRows = legendRows();
  if (legRows > Math.ceil(drawnGroups.length / 2)) { SHORT_LEGEND = true; legRows = legendRows(); }
  var LEG_H = legRows ? SUB_FS + (legRows - 1) * LEG_ROW + LEG_ROW * 0.6 : 0;
  var wordFs = FS, shownWords = F.words.length, shownCaps = F.caption.length;
  function linesOf(list, fs) { var out = []; list.forEach(function (w) { out = out.concat(wrap(w, W - 2 * PAD, fs, Infinity)); }); return out; }
  function held() { return F.words.length + F.caption.length - shownWords - shownCaps; }
  function plotRoom() {
    var wl = linesOf(F.words.slice(0, shownWords), wordFs).length + (held() ? 1 : 0);
    var cl = linesOf(F.caption.slice(0, shownCaps), SUB_FS).length;
    return H - top - (wl * wordFs * 1.3 + PAD / 2) - LEG_H - (cl * SUB_FS * 1.3 + PAD) - PAD - FS * 2.6 - riskH();
  }
  if (plotRoom() < MIN_PLOT) showRisk = false;
  if (plotRoom() < MIN_PLOT) wordFs = SUB_FS;
  while (plotRoom() < MIN_PLOT && (shownCaps > 0 || shownWords > 1)) {
    if (shownCaps > 0) shownCaps--; else shownWords--;
  }
  var capLines = linesOf(F.caption.slice(0, shownCaps), SUB_FS);
  var CAP_H = capLines.length * SUB_FS * 1.3 + PAD;
  var capG = svg.append('g').attr('class', 'lch-km-caption');
  block(capG, capLines, PAD, H - CAP_H, SUB_FS, 'lch-km-cap', true);
  var wordsG = svg.append('g').attr('class', 'lch-km-words');
  top += block(wordsG, linesOf(F.words.slice(0, shownWords), wordFs), PAD, top, wordFs, 'lch-km-word', false);
  function toggleNotes() {
    var open = svg.select('g.lch-km-notes');
    if (!open.empty()) { open.remove(); svg.select('g.lch-km-more').attr('aria-expanded', 'false'); return; }
    var panelTop = +svg.select('g.lch-km-more text').attr('y') + wordFs * 0.5;
    var room = H - panelTop - PAD, fs = SUB_FS, lines = linesOf(F.words.concat(F.caption), fs);
    while (lines.length * fs * 1.3 > room && fs > TYPE_FLOOR) { fs = Math.max(TYPE_FLOOR, fs - 1); lines = linesOf(F.words.concat(F.caption), fs); }
    var panel = svg.append('g').attr('class', 'lch-km-notes').attr('role', 'note');
    panel.append('rect').attr('x', 0).attr('y', panelTop).attr('width', W).attr('height', H - panelTop)
      .attr('fill', options.themeBg || '#fff').attr('fill-opacity', 0.97);
    block(panel, lines, PAD, panelTop + PAD / 2, fs, 'lch-km-note', false);
    svg.select('g.lch-km-more').attr('aria-expanded', 'true').raise();
  }
  if (held()) {
    var moreLabel = 'Show all notes (' + held() + ' more)';
    var more = svg.append('g').attr('class', 'lch-km-more').attr('tabindex', 0).attr('role', 'button')
      .attr('aria-expanded', 'false').attr('aria-label', moreLabel).style('cursor', 'pointer');
    more.append('text').attr('x', PAD).attr('y', top + 0.85 * wordFs * 1.3).attr('font-size', Math.max(TYPE_FLOOR, wordFs))
      .attr('fill', accent).attr('text-decoration', 'underline').text(moreLabel);
    top += wordFs * 1.3;
    more.on('click', function (ev) { ev.stopPropagation(); toggleNotes(); })
      .on('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); ev.stopPropagation(); toggleNotes(); } });
  }
  top += PAD / 2;
  if (!curves.length || !curves.some(function (c) { return c.steps && c.steps.length; })) {
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('font-size', FS).attr('fill', fg).text(options.noDataText || 'No data to display');
    return;
  }
  var legend = svg.append('g').attr('class', 'lch-km-legend');
  var lx = PAD, ly = top + SUB_FS;
  if (drawnGroups.length) {
    drawnGroups.forEach(function (g) {
      var label = legendLabel(g), w = legendW(g);
      if (lx > PAD && lx + w > W - PAD) { lx = PAD; ly += LEG_ROW; }
      var item = legend.append('g').attr('class', 'd3-legend-mark').attr('data-row-idx', g.rowIdx.join(',')).attr('aria-label', label)
        .attr('transform', 'translate(' + lx + ',' + ly + ')').style('cursor', 'pointer');
      item.append('rect').attr('y', -SUB_FS * 0.75).attr('width', SUB_FS).attr('height', SUB_FS * 0.8).attr('rx', 2).attr('fill', colour(g));
      item.append('text').attr('x', SUB_FS * 1.4).attr('font-size', SUB_FS).attr('fill', fg).text(label);
      lx += w;
    });
    top = ly + LEG_ROW * 0.6;
  }
  var RISK_H = riskH();
  var ml = FS * 3.2, mr = PAD * 2, mt = PAD, mb = FS * 2.6 + RISK_H;
  var pw = Math.max(40, W - ml - mr - PAD), ph = Math.max(40, H - top - CAP_H - mt - mb);
  var maxM = d3.max(curves, function (c) { return toMonths(c.cut !== null ? c.cut : (c.steps.length ? c.steps[c.steps.length - 1].t : 0)); }) || 1;
  var endM = Math.max(3, Math.ceil(maxM / 6 - 1e-9) * 6);
  var ticks = (F.tickMonths || []).filter(function (m) { return m <= maxM + 1e-9; });
  var axisTicks = ticks.concat(ticks.indexOf(endM) < 0 && endM - (ticks[ticks.length - 1] || 0) >= 3 ? [endM] : []);
  var x = d3.scaleLinear().domain([0, endM]).range([0, pw]);
  var y = d3.scaleLinear().domain([0, 1]).range([ph, 0]);
  var plot = svg.append('g').attr('class', 'lch-km').attr('transform', 'translate(' + (PAD + ml) + ',' + (top + mt) + ')');
  plot.append('g').attr('class', 'lch-km-y').call(d3.axisLeft(y).ticks(5).tickFormat(pct)).selectAll('text').attr('font-size', SUB_FS).attr('fill', fg);
  var xAxis = plot.append('g').attr('class', 'lch-km-x').attr('transform', 'translate(0,' + ph + ')')
    .call(d3.axisBottom(x).tickValues(axisTicks.length ? axisTicks : x.ticks(5)).tickFormat(function (m) { return num(m); }));
  xAxis.selectAll('text').attr('font-size', SUB_FS).attr('fill', fg);
  plot.append('text').attr('x', pw / 2).attr('y', ph + FS * 2.3).attr('text-anchor', 'middle').attr('font-size', SUB_FS).attr('fill', fg)
    .attr('fill-opacity', 0.75).text('Months since they started');
  plot.selectAll('.domain, .tick line').attr('stroke', fg).attr('stroke-opacity', 0.3);
  function pointsOf(c) {
    var end = c.cut !== null ? c.cut : c.steps[c.steps.length - 1].t;
    var pts = [{ t: 0, S: 1, lo: null, hi: null }];
    c.steps.forEach(function (s) { if (s.t <= end) pts.push(s); });
    pts.push({ t: end, S: pts[pts.length - 1].S, lo: pts[pts.length - 1].lo, hi: pts[pts.length - 1].hi });
    return pts;
  }
  var line = d3.line().curve(d3.curveStepAfter).x(function (p) { return x(toMonths(p.t)); }).y(function (p) { return y(p.S); });
  var band = d3.area().curve(d3.curveStepAfter).defined(function (p) { return p.lo !== null && p.hi !== null; })
    .x(function (p) { return x(toMonths(p.t)); }).y0(function (p) { return y(p.lo); }).y1(function (p) { return y(p.hi); });
  curves.forEach(function (c) {
    if (!c.steps.length) return;
    var pts = pointsOf(c), col = colour(c);
    var lbl = (drawnGroups.length ? legendLabel(c) : 'All customers (' + num(c.n || rows.length) + ')') + ', how long they stay';
    plot.append('path').attr('class', 'lch-km-band').attr('d', band(pts)).attr('fill', col).attr('fill-opacity', 0.16).attr('stroke', 'none')
      .style('pointer-events', 'none');
    plot.append('path').attr('class', 'lch-km-curve d3-mark').attr('data-row-idx', c.rowIdx.join(','))
      .attr('aria-label', lbl)
      .attr('d', line(pts)).attr('fill', 'none').attr('stroke', col).attr('stroke-width', 2).style('cursor', 'pointer');
    plot.append('path').attr('class', 'lch-km-hit d3-mark').attr('data-row-idx', c.rowIdx.join(','))
      .attr('d', line(pts)).attr('fill', 'none').attr('stroke', 'transparent').attr('stroke-width', 12)
      .style('pointer-events', 'stroke').style('cursor', 'pointer');
    if (c.cut !== null) {
      var ex = x(toMonths(pts[pts.length - 1].t)), ey = y(pts[pts.length - 1].S);
      plot.append('line').attr('class', 'lch-km-end').attr('x1', ex).attr('x2', ex).attr('y1', ey - 5).attr('y2', ey + 5)
        .attr('stroke', col).attr('stroke-width', 2).style('pointer-events', 'none');
    }
  });
  plot.append('line').attr('class', 'lch-km-half').attr('x1', 0).attr('x2', pw).attr('y1', y(0.5)).attr('y2', y(0.5))
    .attr('stroke', fg).attr('stroke-opacity', 0.25).attr('stroke-dasharray', '3,3').style('pointer-events', 'none');
  if (showRisk) {
    var strip = plot.append('g').attr('class', 'lch-km-atrisk').attr('transform', 'translate(0,' + (ph + FS * 2.6 + PAD) + ')');
    strip.append('text').attr('x', -ml + 2).attr('y', 0).attr('font-size', SUB_FS).attr('fill', fg).attr('fill-opacity', 0.7).text('Still watched');
    drawnGroups.forEach(function (g, gi) {
      var yy = (gi + 1) * SUB_FS * 1.25;
      strip.append('rect').attr('x', -ml + 2).attr('y', yy - SUB_FS * 0.7).attr('width', SUB_FS * 0.7).attr('height', SUB_FS * 0.7).attr('fill', colour(g));
      ticks.forEach(function (m, ti) {
        if (!g.atTicks || g.atTicks[ti] === undefined) return;
        strip.append('text').attr('x', x(m)).attr('y', yy).attr('text-anchor', 'middle').attr('font-size', SUB_FS).attr('fill', fg)
          .attr('fill-opacity', 0.8).text(num(g.atTicks[ti]));
      });
    });
  }
  if (options.allowTooltips !== false) {
    var tip = d3.llmTooltip(container);
    plot.append('rect').attr('class', 'lch-km-hover').attr('width', pw).attr('height', ph).attr('fill', 'transparent')
      .style('pointer-events', 'all').lower()
      .on('mousemove', function (ev) {
        var m = x.invert(d3.pointer(ev, this)[0]), t = m * DPM;
        var html = '<b>' + num(m) + ' months</b>';
        curves.forEach(function (c) {
          var a = R.at(drawnGroups.length ? c.key : null, t);
          if (!a || a.past) return;
          html += '<br/>' + (drawnGroups.length ? c.key : 'All customers') + ': ' + pct(a.S) + (a.lo !== null && a.lo !== undefined ? ' (' + pct(a.lo) + ' to ' + pct(a.hi) + ')' : '') + ', ' + num(a.nRisk) + ' watched';
        });
        tip.show(html, ev);
      })
      .on('mouseout', function () { tip.hide(); });
  }
}

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

New articles in your inbox

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

This application may no longer respond until reloaded. Reload 🗙