Sum of ReboundsPerGame by Position, as violins
Where do Sum of ReboundsPerGame values bunch up in each Position?
Per-player season averages — points, rebounds, assists, field-goal and three-point percentages, with team, position and age. A wide sports stat line for player comparison, position breakdowns, and shooting-efficiency scatter. Pairs with the NBA Shot Locations dataset.
NBA Player Season Stats: 280 rows, 9 columns. Download the CSV
| PlayerID | Team | Position | AgeYears | Sum of PointsPerGame | Sum of ReboundsPerGame | Sum of AssistsPerGame | FieldGoalPct | ThreePtPct |
|---|---|---|---|---|---|---|---|---|
| NBA1001 | PHX | SG | 25 | 16.1 | 1.7 | 3.2 | 0.449 | 0.39 |
| NBA1002 | MIL | PF | 30 | 17.8 | 4.9 | 1.7 | 0.493 | 0.325 |
| NBA1003 | DEN | PG | 23 | 15.2 | 1.6 | 6.1 | 0.482 | 0.293 |
| NBA1004 | MIL | C | 32 | 2.0 | 11.2 | 1.9 | 0.424 | 0.255 |
| NBA1005 | MIA | PF | 32 | 10.5 | 11.1 | 2.9 | 0.416 | 0.333 |
| NBA1006 | BOS | PG | 33 | 20.0 | 2.4 | 5.5 | 0.416 | 0.358 |
| NBA1007 | GSW | C | 21 | 9.6 | 10.7 | 3.4 | 0.334 | 0.387 |
| NBA1008 | MIL | PF | 19 | 7.8 | 7.7 | 2.0 | 0.326 | 0.357 |
| NBA1009 | DEN | C | 23 | 2.0 | 8.3 | 0.3 | 0.395 | 0.419 |
| NBA1010 | PHI | SG | 24 | 12.6 | 3.0 | 4.1 | 0.467 | 0.321 |

How to read it
A violin is wide where many values sit and thin where few do, so its outline shows the shape a box plot hides. C has the highest median; SG is the most spread out.
The chart's code (49 KB of JavaScript, D3)
It carries its own copies of these helpers: llmText, llmFrameTween, llmRangeBrush, llmSlider, llmNumberEntry, llmSegmented, llmPredictor, llmResponseCurves, llmTerritories, llmCutoff, llmContrast, llmSurvival, llmModelFormat, llmSubgroups, llmSegments, llmGlyphs, llmBreadcrumb, llmKeyframes, llmScrubber, llmValueColumn, llmValueRamp, llmFitLabel, llmThinLabels, llmFitAxisTicks, llmSymlog, llmClipOutliers, llmGeoZoom, llmGeoPointNotes, llmMapLabels, llmGeoMarks, llmPlaceUnit, llmWorldFit, llmRegionFit, llmFlowKey, llmFlowArcs, llmFrameFill, llmTooltip, llmSwarm, llmKde, llmOrbit3d, llmBoundedScale, llmBivariate, llmLegendLayout, llmPager, llmTableFrame, llmGrid, llmUtcDays, llmPeriodGrid, llmTileGrid, llmMermaid, llmDecomp, llmTopN, llmFlipDeck, llmFilterScope, llmDisplayName, llmThemeColors, llmWordCloud.
// bic:keyboard-marks
d3.llmFitLabel = function (sel, widthAccessor, opts) {
var TYPE_FLOOR = 10; // the minimum readable type, px: a string is fitted at no smaller size than a chart may draw it
if (widthAccessor != null && typeof widthAccessor === 'object' && !Array.isArray(widthAccessor)) {
var wobj = widthAccessor, wopts = {};
for (var wk in wobj) if (Object.prototype.hasOwnProperty.call(wobj, wk) && wk !== 'width' && wk !== 'room') wopts[wk] = wobj[wk];
if (opts != null && typeof opts === 'object') {
for (var wk2 in opts) if (Object.prototype.hasOwnProperty.call(opts, wk2)) wopts[wk2] = opts[wk2];
} else if (typeof opts === 'number' && opts > 0 && wopts.fontSize == null) {
wopts.fontSize = Math.max(TYPE_FLOOR, opts);
}
widthAccessor = wobj.width != null ? wobj.width : wobj.room;
opts = wopts;
}
if (typeof sel === 'string' || typeof sel === 'number') {
var so = (opts != null && typeof opts === 'object') ? opts
: ((arguments[3] != null && typeof arguments[3] === 'object') ? arguments[3] : {});
var sfs = Math.max(TYPE_FLOOR, (typeof opts === 'number' && opts > 0) ? opts : (+so.fontSize > 0 ? +so.fontSize : TYPE_FLOOR));
var sopts = {};
for (var sk in so) if (Object.prototype.hasOwnProperty.call(so, sk)) sopts[sk] = so[sk];
sopts.text = String(sel);
sopts.shrinkTo = null;
var holder = null, sn = null;
try {
if (typeof document !== 'undefined' && document && document.body && document.createElementNS) {
holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
holder.setAttribute('width', '0'); holder.setAttribute('height', '0');
holder.style.position = 'absolute'; holder.style.left = '-10000px'; holder.style.visibility = 'hidden';
sn = document.createElementNS('http://www.w3.org/2000/svg', 'text');
holder.appendChild(sn);
document.body.appendChild(holder);
}
} catch (e) { holder = null; sn = null; }
if (!sn) {
sn = { textContent: '', style: {}, fs: sfs,
getAttribute: function (a) { return a === 'font-size' ? String(sn.fs) : null; },
setAttribute: function (a, v) { if (a === 'font-size') sn.fs = +v; } };
}
var fitted;
try {
sn.setAttribute('font-size', String(sfs));
if (so.fontFamily) sn.setAttribute('font-family', String(so.fontFamily));
if (so.fontWeight) sn.setAttribute('font-weight', String(so.fontWeight));
d3.llmFitLabel({ each: function (fn) { fn.call(sn, null, 0); return this; } }, widthAccessor, sopts);
fitted = sn.textContent == null ? '' : String(sn.textContent);
} catch (e) { fitted = String(sel); }
try { if (holder && holder.parentNode) holder.parentNode.removeChild(holder); } catch (e) { /* detached */ }
return fitted;
}
opts = opts || {};
var pad = opts.pad == null ? 4 : opts.pad;
var minWidth = opts.minWidth == null ? 14 : opts.minWidth;
var ell = opts.ellipsis == null ? '\u2026' : opts.ellipsis;
var fallbackFs = opts.fontSize == null ? 10 : opts.fontSize;
var shrinkTo = opts.shrinkTo == null ? null : +opts.shrinkTo;
var overflow = opts.overflow === 'drop' ? 'drop' : 'truncate';
var sibs = Array.isArray(opts.distinctFrom) ? opts.distinctFrom : null;
if (!sel || typeof sel.each !== 'function') return sel;
var DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\uFF10-\uFF19]/;
var JOIN = /[.,'\u00A0\u202F\u2019\u066B\u066C]/;
var GLUED = /[A-Za-z%\u2030]/;
var LEAD = /[+\-\u2212$\u20AC\u00A3\u00A5\u20B9]/;
function numberSafeCut(s, lo) {
if (!(lo > 0) || lo >= s.length) return lo;
var a = s.charAt(lo - 1), b = s.charAt(lo);
var splits = DIGIT.test(a)
? (DIGIT.test(b) || GLUED.test(b) || (JOIN.test(b) && DIGIT.test(s.charAt(lo + 1))))
: (lo >= 2 && JOIN.test(a) && DIGIT.test(s.charAt(lo - 2)) && DIGIT.test(b));
if (!splits) return lo;
var i = lo;
while (i > 0 && (DIGIT.test(s.charAt(i - 1))
|| (i >= 2 && JOIN.test(s.charAt(i - 1)) && DIGIT.test(s.charAt(i - 2))))) i--;
while (i > 0 && LEAD.test(s.charAt(i - 1))) i--;
while (i > 0 && /\s/.test(s.charAt(i - 1))) i--;
return i;
}
function fontSizeOf(node) {
try {
var a = parseFloat(node.getAttribute && node.getAttribute('font-size'));
if (a > 0) return a;
var s = node.style && node.style.fontSize ? parseFloat(node.style.fontSize) : NaN;
if (s > 0) return s;
} catch (e) { /* fall through */ }
return fallbackFs;
}
function setFontSize(node, fs) {
try { if (node.setAttribute) node.setAttribute('font-size', String(fs)); } catch (e) { /* detached */ }
}
function measure(node, txt) {
try {
if (typeof node.getComputedTextLength === 'function') {
var w = node.getComputedTextLength();
if (w > 0) return w;
}
} catch (e) { /* fall through */ }
return String(txt).length * fontSizeOf(node) * 0.6;
}
function ownerSvg(node) {
try {
if (node.ownerSVGElement) return node.ownerSVGElement;
for (var p = node.parentNode; p; p = p.parentNode) {
if (p.nodeName && String(p.nodeName).toLowerCase() === 'svg') return p;
}
} catch (e) { /* detached */ }
return null;
}
function shownText(node) {
var kids = node && node.childNodes;
if (!kids || !kids.length) return node.textContent == null ? '' : String(node.textContent);
var s = '';
for (var c = 0; c < kids.length; c++) {
var k = kids[c];
if (k.nodeType === 3) s += k.nodeValue;
else if (k.nodeType === 1 && String(k.nodeName).toLowerCase() !== 'title') s += shownText(k);
}
return s;
}
function setShown(node, s) {
var kids = node.childNodes, keep = [];
if (kids && kids.length) {
for (var c = 0; c < kids.length; c++) {
if (kids[c].nodeType === 1 && String(kids[c].nodeName).toLowerCase() === 'title') keep.push(kids[c]);
}
}
node.textContent = s;
for (var q = 0; q < keep.length; q++) node.appendChild(keep[q]);
}
function hiddenIn(node, svg) {
try {
for (var p = node, hop = 0; p && hop < 64; p = p.parentNode, hop++) {
if (p.getAttribute && (p.getAttribute('display') === 'none' || p.getAttribute('visibility') === 'hidden')) return true;
if (p.style && (p.style.display === 'none' || p.style.visibility === 'hidden')) return true;
if (p === svg) break;
}
} catch (e) { /* read as shown */ }
return false;
}
function fittedFrom(node) {
return node.__llmFitFrom != null ? node.__llmFitFrom : node.__llmFullLabel;
}
function live(svg, en) {
if (shownText(en.node) !== en.visible) return false;
if (fittedFrom(en.node) != null && String(fittedFrom(en.node)) !== en.full) return false;
try { if (typeof svg.contains === 'function' && !svg.contains(en.node)) return false; } catch (e) { /* keep */ }
return true;
}
function endsWithText(s, t) { return s.length >= t.length && s.slice(s.length - t.length) === t; }
function ending(en, others) {
var f = en.full, n = en.node, E = en.ell;
if (en.drop) return '';
var fits = function (s) { setShown(n, s); return measure(n, s) <= en.room; };
var t = -1;
for (var s = f.length - 1; s >= 1 && t < 0; s--) {
var tl = f.slice(s), alone = true;
for (var o = 0; o < others.length && alone; o++) if (endsWithText(others[o], tl)) alone = false;
if (alone) t = s;
}
if (t < 1) return '';
if (DIGIT.test(f.charAt(t)) && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) {
while (t > 0 && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) t--;
}
if (t < 1) return '';
var ws = t;
while (ws > 0 && !/\s/.test(f.charAt(ws - 1))) ws--;
if (ws > 0 && ws < t && fits(E + f.slice(ws))) t = ws;
else if (!fits(E + f.slice(t))) return '';
var tail = f.slice(t), lo = 0, hi = t - 1;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
if (fits(f.slice(0, mid) + E + tail)) lo = mid; else hi = mid - 1;
}
var head = f.slice(0, numberSafeCut(f, lo)).replace(/\s+$/, '');
if (head.length < 2) head = '';
return head + E + tail;
}
function distinguish(group) {
var g, h, s, en, others;
for (g = 0; g < group.length; g++) {
en = group[g];
others = [];
for (h = 0; h < group.length; h++) if (group[h].full !== en.full) others.push(group[h].full);
try { s = ending(en, others); } catch (e) { s = ''; }
setShown(en.node, s);
en.visible = shownText(en.node);
}
for (g = 0; g < group.length; g++) {
for (h = g + 1; h < group.length; h++) {
var a = group[g], b = group[h];
if (a.visible && a.visible === b.visible && a.full !== b.full) {
setShown(a.node, ''); a.visible = '';
setShown(b.node, ''); b.visible = '';
}
}
}
}
function clashes(reg, svg, en) {
var group = [en], differ = false;
if (hiddenIn(en.node, svg)) return group;
for (var k = reg.length - 1; k >= 0; k--) {
var o = reg[k];
if (o === en || o.visible !== en.visible) continue;
if (!live(svg, o)) { reg.splice(k, 1); continue; }
if (hiddenIn(o.node, svg)) continue;
group.push(o);
if (o.full !== en.full) differ = true;
}
return differ ? group : [en];
}
function settle(node, room) {
var svg = ownerSvg(node);
if (!svg) return;
var reg = svg.__llmFitRegistry;
if (!Array.isArray(reg)) { reg = []; svg.__llmFitRegistry = reg; }
var k;
for (k = reg.length - 1; k >= 0; k--) if (reg[k].node === node) reg.splice(k, 1);
if (reg.length >= (reg.sweepAt || 256)) {
for (k = reg.length - 1; k >= 0; k--) if (!live(svg, reg[k])) reg.splice(k, 1);
reg.sweepAt = Math.max(256, reg.length * 2);
}
var vis = shownText(node);
if (!(room > 0) || !vis) return;
var me = { node: node, full: fittedFrom(node) == null ? vis : String(fittedFrom(node)),
visible: vis, room: room, ell: ell, drop: overflow === 'drop' };
reg.push(me);
var queue = [me];
for (var round = 0; queue.length && round < 32; round++) {
var en = queue.shift();
if (!en.visible) continue;
var group = clashes(reg, svg, en);
if (group.length < 2) continue;
distinguish(group);
for (var g = 0; g < group.length; g++) if (group[g].visible) queue.push(group[g]);
}
}
function fitOne(node, d, i) {
var full, alts = [];
if (opts.text != null) {
try {
full = typeof opts.text === 'function' ? opts.text.call(node, d, i) : opts.text;
} catch (e) { full = ''; }
if (Array.isArray(full)) { alts = full.slice(1); full = full[0]; }
full = full == null ? '' : String(full);
node.__llmFullLabel = full;
node.textContent = full; // authoritative: an EMPTY label must CLEAR the node,
if (!full) return; // never leave the previous frame's text standing
} else {
full = node.__llmFullLabel;
if (full == null) {
full = node.textContent == null ? '' : String(node.textContent);
node.__llmFullLabel = full;
}
if (!full) return;
}
node.__llmFitFrom = null;
var fo = opts.forms;
if (typeof fo === 'function') { try { fo = fo.call(node, d, i); } catch (e) { fo = null; } }
if (fo != null) alts = alts.concat(Array.isArray(fo) ? fo : [fo]);
var cands = [full];
for (var ci = 0; ci < alts.length; ci++) {
var alt = alts[ci] == null ? '' : String(alts[ci]);
if (alt && cands.indexOf(alt) < 0) cands.push(alt);
}
var room;
try {
room = typeof widthAccessor === 'function'
? widthAccessor.call(node, d, i)
: widthAccessor;
} catch (e) { room = 0; }
room = (room == null ? 0 : +room) - pad * 2;
if (!(room > 0) || room < minWidth) { node.textContent = ''; return room; }
if (shrinkTo != null) {
if (node.__llmFullFontSize == null) node.__llmFullFontSize = fontSizeOf(node);
setFontSize(node, node.__llmFullFontSize);
}
node.textContent = full;
var w = measure(node, full);
if (w <= room) return room; // fits whole - done
var c;
for (c = 1; c < cands.length; c++) {
node.textContent = cands[c];
if (measure(node, cands[c]) <= room) { node.__llmFitFrom = cands[c]; return room; }
}
if (shrinkTo != null && shrinkTo > 0) {
for (c = 0; c < cands.length; c++) {
setFontSize(node, node.__llmFullFontSize);
node.textContent = cands[c];
var cur = fontSizeOf(node), wc = measure(node, cands[c]);
if (!(cur > shrinkTo)) break;
var fs = Math.max(shrinkTo, Math.floor((cur * room / wc) * 2) / 2);
for (; fs >= shrinkTo; fs -= 0.5) {
setFontSize(node, fs);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
setFontSize(node, shrinkTo);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
}
if (cands.length > 1) { full = cands[cands.length - 1]; node.__llmFitFrom = full; }
node.textContent = full;
if (overflow === 'drop') { node.textContent = ''; return room; }
var lo = 0, hi = full.length;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
node.textContent = full.slice(0, mid) + ell;
if (measure(node, node.textContent) <= room) lo = mid; else hi = mid - 1;
}
lo = numberSafeCut(full, lo);
if (sibs) {
var shared = 0;
for (var si = 0; si < sibs.length; si++) {
var o = sibs[si] == null ? '' : String(sibs[si]);
if (o === full) continue;
var k = 0;
while (k < o.length && k < full.length && o.charAt(k) === full.charAt(k)) k++;
if (k > shared) shared = k;
}
if (shared > 0 && lo <= shared) {
var a = 1, b = full.length;
while (a < b) {
var m = (a + b) >> 1;
node.textContent = ell + full.slice(m);
if (measure(node, node.textContent) <= room) b = m; else a = m + 1;
}
var inNum = function (i) {
return i > 0 && i < full.length && DIGIT.test(full.charAt(i))
&& (DIGIT.test(full.charAt(i - 1)) || (i >= 2 && JOIN.test(full.charAt(i - 1)) && DIGIT.test(full.charAt(i - 2))));
};
if (inNum(a)) {
var t0 = a;
while (t0 > 0 && (DIGIT.test(full.charAt(t0 - 1)) || (t0 >= 2 && JOIN.test(full.charAt(t0 - 1)) && DIGIT.test(full.charAt(t0 - 2))))) t0--;
node.textContent = ell + full.slice(t0);
a = measure(node, node.textContent) <= room ? t0 : full.length;
}
node.textContent = a < full.length ? ell + full.slice(a) : '';
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : '';
return room;
}
sel.each(function (d, i) {
var room = fitOne(this, d, i);
try { settle(this, room); } catch (e) { /* a failed sibling check leaves the fit as it stands */ }
});
return sel;
};
d3.llmFitAxisTicks = function (axis, opts) {
opts = opts || {};
var sel = axis && typeof axis.selectAll === 'function' ? axis : d3.select(axis);
var ticks = sel.selectAll('.tick').nodes();
if (ticks.length < 2) return { angle: 0, every: 1, shortened: 0 };
var posOf = function (t) {
var m = /translate\(\s*([-0-9.eE]+)/.exec(t.getAttribute('transform') || '');
return m ? +m[1] : 0;
};
var items = ticks.map(function (t) {
var tx = t.querySelector('text');
if (!tx) return null;
if (tx.__llmFullName == null) {
var title = tx.querySelector('title');
var shown = '';
for (var i = 0; i < tx.childNodes.length; i++) if (tx.childNodes[i].nodeType === 3) shown += tx.childNodes[i].nodeValue;
tx.__llmFullName = title ? title.textContent : shown;
}
return { tick: t, text: tx, x: posOf(t), name: String(tx.__llmFullName).trim() };
}).filter(Boolean);
if (items.length < 2) return { angle: 0, every: 1, shortened: 0 };
items.sort(function (a, b) { return a.x - b.x; });
var step = Infinity;
for (var i = 1; i < items.length; i++) step = Math.min(step, Math.abs(items[i].x - items[i - 1].x));
var TYPE_FLOOR = 10; // the minimum readable type, px: labels are measured (and drawn) no smaller
var fs = Math.max(TYPE_FLOOR, opts.fontSize || parseFloat(items[0].text.getAttribute('font-size') || sel.attr('font-size') || '') || 11);
var left = opts.left;
if (left == null) {
var acc = 0, n = sel.node();
for (; n && n.nodeType === 1 && String(n.nodeName).toLowerCase() !== 'svg'; n = n.parentNode) {
var tf = (n.getAttribute('transform') || '').trim();
if (!tf) continue;
var tm = /^translate\(\s*([-0-9.eE]+)(?:[\s,]+[-0-9.eE]+)?\s*\)$/.exec(tf);
if (!tm) { acc = null; break; }
acc += +tm[1];
}
left = acc != null && n && n.nodeType === 1 && isFinite(acc) ? acc : null;
}
var p = d3.llmFitAxisTicks.plan(items.map(function (d) { return d.name; }),
{ step: step, room: opts.room == null ? 60 : opts.room, left: left, first: items[0].x, fontSize: fs,
gap: opts.gap == null ? 4 : opts.gap });
items.forEach(function (d, i) {
var tx = d3.select(d.text);
var shown = p.labels[i];
tx.selectAll('title').remove();
tx.text(shown == null ? d.name : shown);
if (shown == null) tx.style('visibility', 'hidden');
else tx.style('visibility', null);
if (shown !== d.name) tx.append('title').text(d.name);
if (p.angle === 0) tx.attr('transform', null).attr('text-anchor', 'middle').style('text-anchor', 'middle').attr('dx', null);
else if (p.angle === 45) tx.attr('transform', 'rotate(-45)').attr('text-anchor', 'end').style('text-anchor', 'end')
.attr('x', -4).attr('y', 6).attr('dx', null).attr('dy', '0.35em');
else tx.attr('transform', 'rotate(-90)').attr('text-anchor', 'end').style('text-anchor', 'end')
.attr('x', -8).attr('y', 0).attr('dx', null).attr('dy', '0.35em');
});
return { angle: p.angle, every: p.every, shortened: p.shortened };
};
d3.llmFitAxisTicks.plan = function (names, o) {
var TYPE_FLOOR = 10;
var fs = Math.max(TYPE_FLOOR, o.fontSize || 11), gap = o.gap == null ? 4 : o.gap, room = Math.max(0, o.room == null ? 60 : o.room);
var step = o.step > 0 ? o.step : 1;
var bounded = o.left != null && isFinite(o.left);
var first = o.first == null ? step / 2 : o.first;
var reach = function (i) { return Math.max(0, o.left + first + i * step - 2); };
var cw = 0.6 * fs; // the estimate the gate measures with
var n = names.length;
var line = 1.1 * fs; // neighbouring angled baselines kept this far apart
var candidates = [];
[0, 45, 90].forEach(function (angle) {
var sin = Math.sin(angle * Math.PI / 180);
for (var k = 1; k <= n; k++) {
if (angle > 0 && step * k * sin < line) continue;
var lenPx = angle === 0 ? step * k - gap : room / sin;
var shownIdx = [];
for (var i = 0; i < n; i += k) shownIdx.push(i);
var chars = Math.floor(lenPx / cw);
if (angle === 45 && bounded) {
var cos = Math.cos(angle * Math.PI / 180);
chars = shownIdx.map(function (i) { return Math.floor(Math.min(lenPx, reach(i) / cos) / cw); });
if (Math.min.apply(null, chars) < 3) continue;
} else if (chars < 3) continue;
var cut = d3.llmFitAxisTicks.shorten(shownIdx.map(function (i) { return names[i]; }), chars);
if (!cut) continue;
var labels = names.map(function () { return null; });
shownIdx.forEach(function (i, j) { labels[i] = cut.labels[j]; });
candidates.push({ angle: angle, every: k, labels: labels, shortened: cut.shortened, lost: cut.lost });
break;
}
});
if (!candidates.length) {
var labels = names.map(function (s, i) { return i === 0 ? s : null; });
return { angle: 90, every: n, labels: labels, shortened: 0 };
}
candidates.sort(function (a, b) { return a.every - b.every || a.lost - b.lost || a.angle - b.angle; });
var best = candidates[0];
return { angle: best.angle, every: best.every, labels: best.labels, shortened: best.shortened };
};
d3.llmFitAxisTicks.shorten = function (names, chars) {
var E = '\u2026';
var lost = 0, shortened = 0;
var unique = function (arr) { return new Set(arr).size === arr.length; };
var cap = Array.isArray(chars) ? function (i) { return chars[i]; } : function () { return chars; };
if (names.every(function (s, i) { return s.length <= cap(i); })) return { labels: names.slice(), shortened: 0, lost: 0 };
if (!unique(names)) {
var heads = names.map(function (s, i) { return s.length <= cap(i) ? s : s.slice(0, Math.max(1, cap(i) - 1)) + E; });
heads.forEach(function (h, i) { if (h !== names[i]) { shortened++; lost += names[i].length - h.length + 1; } });
return { labels: heads, shortened: shortened, lost: lost };
}
var head = names.map(function (s, i) { return s.length <= cap(i) ? s : s.slice(0, cap(i) - 1).replace(/\s+$/, '') + E; });
if (unique(head)) {
head.forEach(function (h, i) { if (h !== names[i]) { shortened++; lost += names[i].length - h.length + 1; } });
return { labels: head, shortened: shortened, lost: lost };
}
var starts = function (s) {
var at = [];
for (var i = 1; i < s.length; i++) {
var a = s.charAt(i - 1), b = s.charAt(i);
if (/\s/.test(b)) continue;
if (/\s/.test(a) || (/[0-9]/.test(b) && !/[0-9]/.test(a)) || (/[A-Za-z]/.test(b) && /[0-9]/.test(a))) at.push(i);
}
return at; // ascending
};
var tailAt = function (s, k) { // the k-th shortest end that starts a word or a number (k = 1 the last one)
var at = starts(s);
return k <= at.length ? s.slice(at[at.length - k]) : s;
};
var most = names.reduce(function (a, s) { return Math.max(a, starts(s).length); }, 0);
for (var k = 1; k <= most; k++) {
var ends = names.map(function (s) { return tailAt(s, k); });
if (!unique(ends)) continue;
var fits = true;
var both = names.map(function (s, i) {
if (s.length <= cap(i)) return s;
var h = cap(i) - 1 - ends[i].length;
if (h < 0) { fits = false; return s; }
return s.slice(0, h).replace(/\s+$/, '') + E + ends[i];
});
if (!fits) return null;
if (!unique(both)) continue;
both.forEach(function (b, i) { if (b !== names[i]) { shortened++; lost += names[i].length - b.length + 1; } });
return { labels: both, shortened: shortened, lost: lost };
}
return null;
};
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.llmSwarm = function (items, opts) {
opts = opts || {};
var list = Array.isArray(items) ? items : Array.from(items || []);
var valueOf = typeof opts.value === 'function' ? opts.value : function (d) { return d; };
var centerOf = typeof opts.center === 'function' ? opts.center : function () { return opts.center == null ? 0 : opts.center; };
var widthOf = typeof opts.width === 'function' ? opts.width : function () { return opts.width; };
var groupOf = typeof opts.group === 'function' ? opts.group : function (d, i) { return centerOf(d, i); };
var maxR = opts.radius > 0 ? opts.radius : 4;
var minR = opts.minRadius > 0 ? Math.min(opts.minRadius, maxR) : Math.min(1.5, maxR);
var pad = opts.padding >= 0 ? opts.padding : 0.5;
var side = opts.side === 'positive' || opts.side === 'negative' ? opts.side : 'both';
var alongX = opts.orient === 'x';
var nodes = new Array(list.length);
var groups = new Map();
for (var i = 0; i < list.length; i++) {
var d = list[i];
var v = Number(valueOf(d, i));
var c = Number(centerOf(d, i));
var w = Number(widthOf(d, i));
var node = { data: d, index: i, x: NaN, y: NaN, r: maxR, placed: false, v: v, c: c, w: w, o: 0 };
nodes[i] = node;
if (!isFinite(v) || !isFinite(c)) continue;
var key = groupOf(d, i);
var g = groups.get(key);
if (!g) { g = []; groups.set(key, g); }
g.push(node);
}
var groupList = Array.from(groups.values());
groupList.forEach(function (g) { g.sort(function (a, b) { return a.v - b.v || a.index - b.index; }); });
function densestFits(r) {
var dia = 2 * r + pad;
for (var gi = 0; gi < groupList.length; gi++) {
var g = groupList[gi];
var room = isFinite(g[0].w) && g[0].w > 0 ? g[0].w : 0;
var cap = Math.max(1, Math.floor(room / (dia * 0.866)));
for (var lo = 0, hi = 0; hi < g.length; hi++) {
while (g[hi].v - g[lo].v >= dia) lo++;
if (hi - lo + 1 > cap) return false;
}
}
return true;
}
function layout(r) {
var dia = 2 * r + pad, loose = r + pad, missed = 0;
for (var gi = 0; gi < groupList.length; gi++) {
var g = groupList[gi];
var half = (isFinite(g[0].w) && g[0].w > 0 ? g[0].w / 2 : 0) - r;
var placed = [], head = 0, left = [];
for (var k = 0; k < g.length; k++) {
var n = g[k];
while (head < placed.length && n.v - placed[head].v >= dia) head++;
var iv = [];
for (var j = head; j < placed.length; j++) {
var dv = n.v - placed[j].v;
var dx = Math.sqrt(dia * dia - dv * dv);
iv.push([placed[j].o - dx, placed[j].o + dx]);
}
var best = nearestFree(iv, half, placed.length % 2 === 0);
if (best === null) { n.o = 0; n.placed = false; missed++; left.push(n); continue; }
n.o = best; n.placed = true;
placed.push(n);
}
if (!left.length) continue;
var crowded = [], lo2 = 0, headC = 0, spread = 0;
for (var u = 0; u < left.length; u++) {
var p = left[u], iv2 = [];
while (lo2 < placed.length && p.v - placed[lo2].v >= loose) lo2++;
for (var s = lo2; s < placed.length && placed[s].v - p.v < loose; s++) addGap(iv2, p, placed[s], loose);
while (headC < crowded.length && p.v - crowded[headC].v >= loose) headC++;
for (var t2 = headC; t2 < crowded.length; t2++) addGap(iv2, p, crowded[t2], loose);
var spot = nearestFree(iv2, half, crowded.length % 2 === 0);
if (spot === null) {
spread++;
p.o = half > 0 ? (((spread * 0.6180339887) % 1) * 2 - 1) * half : 0;
continue;
}
p.o = spot;
crowded.push(p);
}
}
return missed;
}
function addGap(iv, p, q, spacing) {
var dv = p.v - q.v;
if (Math.abs(dv) >= spacing) return;
var dx = Math.sqrt(spacing * spacing - dv * dv);
iv.push([q.o - dx, q.o + dx]);
}
function nearestFree(iv, half, preferPositive) {
if (half < 0) return iv.length === 0 ? 0 : null;
var lo = side === 'positive' ? 0 : -half, hi = side === 'negative' ? 0 : half;
iv.sort(function (a, b) { return a[0] - b[0]; });
var merged = [];
for (var m = 0; m < iv.length; m++) {
var last = merged[merged.length - 1];
if (last && iv[m][0] < last[1]) { if (iv[m][1] > last[1]) last[1] = iv[m][1]; }
else merged.push([iv[m][0], iv[m][1]]);
}
var best = null, from = -Infinity;
for (var q = 0; q <= merged.length; q++) {
var to = q < merged.length ? merged[q][0] : Infinity;
var a = Math.max(from, lo), b = Math.min(to, hi);
if (a <= b) {
var cand = a > 0 ? a : (b < 0 ? b : 0);
if (best === null || Math.abs(cand) < Math.abs(best) - 1e-9
|| (Math.abs(Math.abs(cand) - Math.abs(best)) <= 1e-9 && (preferPositive ? cand > best : cand < best))) best = cand;
}
if (q < merged.length) from = merged[q][1];
}
return best;
}
var r = maxR;
while (r > minR && !densestFits(r)) r = Math.max(minR, r * 0.9);
var unplaced = layout(r);
while (unplaced > 0 && r > minR) {
r = Math.max(minR, r * 0.9);
unplaced = layout(r);
}
for (var t = 0; t < nodes.length; t++) {
var nd = nodes[t];
nd.r = r;
if (!isFinite(nd.v) || !isFinite(nd.c)) continue;
if (alongX) { nd.x = nd.v; nd.y = nd.c + nd.o; }
else { nd.x = nd.c + nd.o; nd.y = nd.v; }
}
var total = nodes.filter(function (nd) { return isFinite(nd.v) && isFinite(nd.c); }).length;
var fmt = function (x) { try { return Number(x).toLocaleString(opts.locale || undefined); } catch (e) { return String(x); } };
return {
nodes: nodes.map(function (nd) { return { data: nd.data, index: nd.index, x: nd.x, y: nd.y, r: nd.r, placed: nd.placed }; }),
radius: r,
unplaced: unplaced,
total: total,
note: unplaced > 0 ? fmt(unplaced) + ' of ' + fmt(total) + ' dots overlap others at their value: too many to separate at this size' : ''
};
};
d3.llmKde = function (values, opts) {
opts = opts || {};
var acc = typeof opts.value === 'function' ? opts.value : function (x) { return x; };
var list = Array.isArray(values) ? values : Array.from(values || []);
var xs = [];
for (var i = 0; i < list.length; i++) {
var raw = acc(list[i], i);
if (raw === null || raw === undefined || raw === '') continue;
var num = Number(raw);
if (isFinite(num)) xs.push(num);
}
xs.sort(function (a, b) { return a - b; });
var n = xs.length;
var none = { points: [], bandwidth: NaN, peak: 0, n: n, lo: n ? xs[0] : NaN, hi: n ? xs[n - 1] : NaN };
if (n < 2 || xs[0] === xs[n - 1]) return none;
var mean = 0;
for (var a = 0; a < n; a++) mean += xs[a];
mean /= n;
var ss = 0;
for (var b = 0; b < n; b++) ss += (xs[b] - mean) * (xs[b] - mean);
var sd = Math.sqrt(ss / (n - 1));
function quant(p) { var h = (n - 1) * p, f = Math.floor(h); return xs[f] + (xs[Math.min(f + 1, n - 1)] - xs[f]) * (h - f); }
var iqr = quant(0.75) - quant(0.25);
var spread = iqr > 0 ? Math.min(sd, iqr / 1.34) : sd;
var bw = opts.bandwidth > 0 ? Number(opts.bandwidth) : 0.9 * spread * Math.pow(n, -0.2);
if (!(bw > 0) || !isFinite(bw)) return none;
var cut = opts.cut >= 0 ? Number(opts.cut) : 2;
var from = xs[0] - cut * bw, to = xs[n - 1] + cut * bw;
var dom = opts.domain;
if (dom && dom.length === 2 && isFinite(dom[0]) && isFinite(dom[1])) {
from = Math.max(from, Math.min(dom[0], dom[1]));
to = Math.min(to, Math.max(dom[0], dom[1]));
}
if (!(to > from)) return none;
var wanted = Math.ceil(2 * (to - from) / bw), given = opts.steps >= 8;
var steps = given ? Math.floor(opts.steps) : Math.min(1024, Math.max(64, wanted));
var ts = [];
if (!given && wanted > 1024) {
var link = Math.max(6, 2 * cut + 2) * bw, runs = [], total = 0, first = 0;
for (var e = 1; e <= n; e++) {
if (e < n && xs[e] - xs[e - 1] <= link) continue;
var rf = Math.max(from, xs[first] - cut * bw), rt = Math.min(to, xs[e - 1] + cut * bw);
if (rt > rf) { var rk = Math.max(16, Math.ceil(4 * (rt - rf) / bw)); runs.push({ f: rf, t: rt, k: rk }); total += rk; }
first = e;
}
for (var u = 0; u < runs.length; u++) {
var run = runs[u], rn = total > 1024 ? Math.max(8, Math.floor(run.k * 1024 / total)) : run.k;
if (u > 0) {
var pe = runs[u - 1].t, d = Math.min(bw, (run.f - pe) / 9), w;
for (w = 1; w <= 4; w++) ts.push(pe + w * d);
for (w = 4; w >= 1; w--) ts.push(run.f - w * d);
}
for (var q = 0; q <= rn; q++) ts.push(q === rn ? run.t : run.f + (run.t - run.f) * q / rn);
}
}
if (!ts.length) for (var g = 0; g <= steps; g++) ts.push(g === steps ? to : from + (to - from) * g / steps);
var epa = opts.kernel === 'epanechnikov';
var scale = epa ? 1 / (n * bw) : 1 / (n * bw * Math.sqrt(2 * Math.PI));
var pts = new Array(ts.length), peak = 0;
for (var k = 0; k < ts.length; k++) {
var t = ts[k], s = 0;
for (var j = 0; j < n; j++) {
var z = (t - xs[j]) / bw;
s += epa ? (z > -1 && z < 1 ? 0.75 * (1 - z * z) : 0) : Math.exp(-0.5 * z * z);
}
var dens = s * scale;
pts[k] = { v: t, d: dens };
if (dens > peak) peak = dens;
}
return { points: pts, bandwidth: bw, peak: peak, n: n, lo: xs[0], hi: xs[n - 1] };
};
d3.llmThemeColors = function (options) {
options = options || {};
var pick = function (v, d) { return (typeof v === 'string' && v && v !== 'transparent') ? v : d; };
var bg = pick(options.backgroundColor, pick(options.themeBg, '#ffffff'));
var fg = pick(options.themeFg, '#252423');
var hc = !!options.isHighContrast;
var pal = (options.palette && options.palette.length) ? options.palette.slice() : ['#4C78A8', '#F58518', '#54A24B', '#E45756', '#72B7B2', '#B279A2', '#FF9DA6', '#9D755D'];
var rgb = function (c) { var x = null; try { x = d3.rgb(c); } catch (e) { x = null; } return x && isFinite(x.r) ? x : d3.rgb(128, 128, 128); };
var lum = function (c) {
var r = rgb(c);
var f = function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r.r) + 0.7152 * f(r.g) + 0.0722 * f(r.b);
};
var contrast = function (a, b) { var x = lum(a) + 0.05, y = lum(b) + 0.05; return x > y ? x / y : y / x; };
var legible = function (col, floor) {
floor = floor || 3;
var c = d3.lab(rgb(col));
var step = lum(bg) > 0.5 ? -3 : 3; // a light background darkens the hue, a dark one lightens it
for (var i = 0; i < 34 && contrast(c.formatHex(), bg) < floor; i++) c.l = Math.max(0, Math.min(100, c.l + step));
return c.formatHex();
};
var good = hc ? pick(options.themeAccent, fg) : legible('#2e7d32');
var bad = hc ? fg : legible('#c62828');
var slot = function (value, n) {
var h = 2166136261, text = String(value);
for (var i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h % n;
};
var deltaE2000 = function (x, y) {
var rad = Math.PI / 180, L1 = x.l, a1 = x.a, b1 = x.b, L2 = y.l, a2 = y.a, b2 = y.b;
var C1 = Math.sqrt(a1 * a1 + b1 * b1), C2 = Math.sqrt(a2 * a2 + b2 * b2), Cm = (C1 + C2) / 2;
var G = 0.5 * (1 - Math.sqrt(Math.pow(Cm, 7) / (Math.pow(Cm, 7) + Math.pow(25, 7))));
var a1p = (1 + G) * a1, a2p = (1 + G) * a2;
var C1p = Math.sqrt(a1p * a1p + b1 * b1), C2p = Math.sqrt(a2p * a2p + b2 * b2);
var hp = function (bb, ap) { if (bb === 0 && ap === 0) return 0; var hh = Math.atan2(bb, ap) / rad; return hh < 0 ? hh + 360 : hh; };
var h1p = hp(b1, a1p), h2p = hp(b2, a2p);
var dLp = L2 - L1, dCp = C2p - C1p, dhp = 0;
if (C1p * C2p !== 0) { dhp = h2p - h1p; if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360; }
var dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhp * rad / 2);
var Lm = (L1 + L2) / 2, Cmp = (C1p + C2p) / 2, hm = h1p + h2p;
if (C1p * C2p !== 0) { if (Math.abs(h1p - h2p) > 180) hm += (hm < 360 ? 360 : -360); hm /= 2; }
var T = 1 - 0.17 * Math.cos((hm - 30) * rad) + 0.24 * Math.cos(2 * hm * rad) + 0.32 * Math.cos((3 * hm + 6) * rad) - 0.2 * Math.cos((4 * hm - 63) * rad);
var dTh = 30 * Math.exp(-Math.pow((hm - 275) / 25, 2));
var Rc = 2 * Math.sqrt(Math.pow(Cmp, 7) / (Math.pow(Cmp, 7) + Math.pow(25, 7)));
var Sl = 1 + 0.015 * Math.pow(Lm - 50, 2) / Math.sqrt(20 + Math.pow(Lm - 50, 2)), Sc = 1 + 0.045 * Cmp, Sh = 1 + 0.015 * Cmp * T;
var Rt = -Math.sin(2 * dTh * rad) * Rc;
var tl = dLp / Sl, tc = dCp / Sc, th = dHp / Sh;
return Math.sqrt(tl * tl + tc * tc + th * th + Rt * tc * th);
};
var order = null, pool = null, near = null;
var growOrder = function (count) {
if (!order) {
order = pal.map(function (c) { return rgb(c).formatHex(); });
var taken = order.map(function (c) { return d3.lab(c); });
var seenHex = {};
order.forEach(function (c) { seenHex[c] = 1; });
pool = [];
pal.forEach(function (c) {
var h = d3.hcl(rgb(c));
if (!isFinite(h.h)) h.h = 0;
var chroma = Math.max(isFinite(h.c) ? h.c : 0, 35);
[h.l, 38, 52, 66].forEach(function (L) {
for (var k = 1; k < 18; k++) {
var cc = d3.hcl((h.h + k * 20) % 360, chroma, L);
while (!cc.displayable() && cc.c > 20) cc.c -= 5;
if (!cc.displayable()) continue;
var hl = d3.hsl(cc).l;
if (!(hl > 0.15 && hl < 0.85)) continue;
var hx = cc.formatHex();
if (seenHex[hx]) continue;
seenHex[hx] = 1;
pool.push({ hex: hx, lab: d3.lab(hx) });
}
});
});
near = pool.map(function (q) {
var m = Infinity;
for (var t = 0; t < taken.length; t++) m = Math.min(m, deltaE2000(q.lab, taken[t]));
return m;
});
}
while (order.length < count && pool.length) {
var best = 0;
for (var q = 1; q < pool.length; q++) if (near[q] > near[best]) best = q;
var picked = pool.splice(best, 1)[0];
near.splice(best, 1);
order.push(picked.hex);
for (var r2 = 0; r2 < pool.length; r2++) near[r2] = Math.min(near[r2], deltaE2000(pool[r2].lab, picked.lab));
}
for (var round = 1; order.length < count && round < 40; round++) {
for (var e = 0; e < pal.length && order.length < count; e++) {
var hc = d3.hsl(pal[e]);
if (!isFinite(hc.h)) hc.h = 0;
var step = Math.ceil(round / 2) * 0.12 * (round % 2 ? 1 : -1);
hc.l = Math.max(0.12, Math.min(0.88, hc.l + step));
hc.h = (hc.h + round * 7) % 360;
var cx = hc.formatHex();
if (order.indexOf(cx) < 0) order.push(cx);
}
}
};
var extended = function (count) {
if (pal.length >= count) return pal.slice();
growOrder(count);
return pal.slice().concat(order.slice(pal.length, count));
};
var memory = function () {
var m = d3.__lchCategorySlots;
if (!m || !Array.isArray(m.groups)) { m = { groups: [] }; try { d3.__lchCategorySlots = m; } catch (e) { /* a frozen d3: no memory */ } }
return m;
};
var categories = function (values) {
var seen = {}, list = [];
(values || []).forEach(function (v) { var k = v === null || v === undefined ? '' : String(v); if (!seen[k]) { seen[k] = 1; list.push(k); } });
list.sort();
var mem = memory(), group = null, best = 0;
mem.groups.forEach(function (g) {
var shared = 0;
list.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(g.slots, k)) shared++; });
if (shared > best) { best = shared; group = g; }
});
if (!group) {
group = { slots: {}, used: {}, size: 0 };
mem.groups.push(group);
if (mem.groups.length > 32) mem.groups.shift();
}
var fresh = list.filter(function (k) { return !Object.prototype.hasOwnProperty.call(group.slots, k); });
var total = group.size + fresh.length;
var cols = extended(Math.max(list.length, total));
var n = cols.length;
fresh.forEach(function (k) {
if (group.size >= 2000) return; // a category this long is not a palette's job: past it, a value is placed but not remembered
var i = 0;
while (group.used[i] && i < n) i++;
group.used[i] = 1;
group.slots[k] = i;
group.size++;
});
var map = {};
list.forEach(function (k) {
var i = Object.prototype.hasOwnProperty.call(group.slots, k) ? group.slots[k] : slot(k, n);
if (i >= cols.length) cols = extended(i + 1);
map[k] = cols[i % cols.length];
});
return function (v) {
var k = v === null || v === undefined ? '' : String(v);
return map[k] || cols[slot(k, n)];
};
};
return { bg: bg, fg: fg, good: good, bad: bad, categories: categories, legible: function (c) { return legible(c); }, contrast: contrast, palette: pal };
};
function render(container, data, options) {
container.replaceChildren();
const W = options.width, H = options.height;
const fg = options.themeFg || 'currentColor';
const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
const noData = () => {
svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('fill', fg)
.text((typeof options.noDataText === 'string' && options.noDataText) ? options.noDataText : 'No data to display');
};
const pIdx = data.columns.findIndex(c => c.name === 'Position');
const vIdx = data.columns.findIndex(c => c.name === 'Sum of ReboundsPerGame');
const rIdx = data.columns.findIndex(c => c.name === '__rowIdx__');
if (pIdx < 0) throw new Error('INVALID:column "Position" not found');
if (vIdx < 0) throw new Error('INVALID:column "Sum of ReboundsPerGame" not found');
const nf = new Intl.NumberFormat(options.cultureCode, { maximumFractionDigits: 2 });
const valid = [];
let skipped = 0;
data.rows.forEach((r, i) => {
const raw = r[vIdx];
const v = raw == null || raw === '' ? NaN : +raw;
if (!isFinite(v) || r[pIdx] == null) { skipped++; return; }
valid.push({ v, cat: String(r[pIdx]), i: rIdx >= 0 ? +r[rIdx] : i });
});
if (!valid.length) { noData(); return; }
const byCat = d3.group(valid, d => d.cat);
const stats = [...byCat].map(([cat, pts]) => {
const vs = pts.map(p => p.v).sort(d3.ascending);
return { cat, pts, vs, n: vs.length, med: d3.median(vs), mean: d3.mean(vs),
q1: d3.quantile(vs, 0.25), q3: d3.quantile(vs, 0.75), idxs: pts.map(p => p.i),
dense: vs.length >= 20 && vs[0] !== vs[vs.length - 1] };
});
stats.sort((a, b) => d3.descending(a.med, b.med) || d3.descending(a.mean, b.mean) || d3.ascending(a.cat, b.cat));
let tied = false;
for (let k = 1; k < stats.length; k++) if (stats[k].med === stats[k - 1].med) tied = true;
const cats = stats.map(s => s.cat);
const T = d3.llmThemeColors(options);
const colorOf = T.categories(cats);
const overallMed = d3.median(valid, d => d.v);
const small = stats.filter(s => !s.dense);
const notes = [];
notes.push('Violin: kernel density of each player value; box: quartiles with median line');
if (small.length) notes.push(small.map(s => `${s.cat}: ${s.n} samples, under the 20-sample floor - drawn as points`).join('; '));
if (skipped) notes.push(`${skipped} rows are not drawn: no value for Rebounds per Game`);
const narrow = W < 500;
const rightM = narrow ? 8 : Math.max(96, Math.min(W * 0.14, 120));
const margin = { top: 14 + notes.length * 15 + 8, right: rightM, bottom: narrow ? 96 : 76, left: 56 };
const plotW = Math.max(40, W - margin.left - margin.right), plotH = Math.max(40, H - margin.top - margin.bottom);
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
notes.forEach((t, k) => {
const s = svg.append('text').attr('x', 8).attr('y', 14 + k * 15).attr('font-size', 11).attr('fill', fg).attr('fill-opacity', 0.85).text(t);
d3.llmFitLabel(s, W - 16, { text: t });
s.append('title').text(t);
});
const ext = d3.extent(valid, d => d.v);
const pad = (ext[1] - ext[0] || 1) * 0.06;
const y = d3.scaleLinear().domain([Math.max(0, ext[0] - pad), ext[1] + pad]).nice().range([plotH, 0]);
const x = d3.scaleBand().domain(cats).range([0, plotW]).padding(0.15);
g.append('g').selectAll('line').data(y.ticks(6)).join('line')
.attr('x1', 0).attr('x2', plotW).attr('y1', d => y(d)).attr('y2', d => y(d))
.attr('stroke', fg).attr('stroke-opacity', 0.12);
g.append('g').call(d3.axisLeft(y).ticks(6).tickFormat(d => nf.format(d)))
.call(a => a.selectAll('text').attr('fill', fg).attr('font-size', 11))
.call(a => a.selectAll('line,path').attr('stroke', fg).attr('stroke-opacity', 0.5));
const xAxis = g.append('g').attr('transform', `translate(0,${plotH})`).call(d3.axisBottom(x));
xAxis.selectAll('text').attr('fill', fg).attr('font-size', 11);
xAxis.selectAll('line,path').attr('stroke', fg).attr('stroke-opacity', 0.5);
const rowIdxByCat = new Map(stats.map(s => [s.cat, s.idxs]));
xAxis.selectAll('.tick').each(function (cat) {
d3.select(this).select('text').attr('class', 'd3-axis-filter').style('cursor', 'pointer')
.attr('data-row-idx', (rowIdxByCat.get(cat) || []).join(','));
});
d3.llmFitAxisTicks(xAxis, { room: Math.max(30, margin.bottom - 30) });
const kdes = new Map();
stats.forEach(s => { if (s.dense) kdes.set(s.cat, d3.llmKde(s.vs, { domain: y.domain() })); });
const maxPeak = d3.max([...kdes.values()], k => k.peak) || 1;
const wScale = d3.scaleLinear([0, maxPeak], [0, x.bandwidth() / 2]);
const tip = options.allowTooltips !== false ? d3.llmTooltip(container) : null;
const tipHtml = s => `<b>${s.cat}</b><br/>Players: ${s.n}<br/>Median: ${nf.format(s.med)}<br/>Q1 to Q3: ${nf.format(s.q1)} to ${nf.format(s.q3)}<br/>Range: ${nf.format(s.vs[0])} to ${nf.format(s.vs[s.n - 1])}`;
const hook = (sel, htmlFn) => {
if (!tip) return;
sel.on('mousemove', (event, d) => tip.show(htmlFn(d), event)).on('mouseleave', () => tip.hide());
};
const dense = stats.filter(s => s.dense);
const line = d3.line().x(p => p[0]).y(p => p[1]);
g.append('g').selectAll('path.d3-mark').data(dense).join('path')
.attr('class', 'd3-mark')
.attr('data-row-idx', d => d.idxs.join(','))
.style('cursor', 'pointer')
.attr('fill', d => T.legible(colorOf(d.cat))).attr('fill-opacity', 0.85)
.attr('stroke', fg).attr('stroke-opacity', 0.6).attr('stroke-width', 1)
.attr('d', d => {
const k = kdes.get(d.cat), cx = x(d.cat) + x.bandwidth() / 2;
const pts = k.points.filter(p => isFinite(p.d));
const left = pts.map(p => [cx - wScale(p.d), y(p.v)]);
const right = pts.slice().reverse().map(p => [cx + wScale(p.d), y(p.v)]);
return line(left.concat(right)) + 'Z';
})
.call(sel => hook(sel, tipHtml));
const boxG = g.append('g').style('pointer-events', 'none');
dense.forEach(s => {
const cx = x(s.cat) + x.bandwidth() / 2, bw = Math.min(10, x.bandwidth() * 0.12);
const iqr = s.q3 - s.q1;
const lo = d3.min(s.vs.filter(v => v >= s.q1 - 1.5 * iqr)), hi = d3.max(s.vs.filter(v => v <= s.q3 + 1.5 * iqr));
boxG.append('line').attr('x1', cx).attr('x2', cx).attr('y1', y(lo)).attr('y2', y(hi)).attr('stroke', fg).attr('stroke-width', 1.5);
boxG.append('rect').attr('x', cx - bw / 2).attr('y', y(s.q3)).attr('width', bw).attr('height', Math.max(1, y(s.q1) - y(s.q3)))
.attr('fill', options.themeBg || '#fff').attr('stroke', fg).attr('stroke-width', 1.2);
boxG.append('line').attr('x1', cx - bw / 2).attr('x2', cx + bw / 2).attr('y1', y(s.med)).attr('y2', y(s.med)).attr('stroke', fg).attr('stroke-width', 2);
});
small.forEach(s => {
const pts = s.pts.map(p => ({ v: p.v, cat: s.cat, i: p.i }));
const sw = d3.llmSwarm(pts, { value: p => y(p.v), center: () => x(s.cat) + x.bandwidth() / 2,
width: x.bandwidth(), radius: 3.5, minRadius: 1.5, locale: options.cultureCode });
const nodes = sw.nodes.filter(n => isFinite(n.x));
g.append('g').selectAll('circle.d3-mark').data(nodes).join('circle')
.attr('class', 'd3-mark').attr('data-row-idx', n => n.data ? n.data.i : n.i)
.style('cursor', 'pointer')
.attr('cx', n => n.x).attr('cy', n => n.y).attr('r', sw.radius)
.attr('fill', T.legible(colorOf(s.cat))).attr('stroke', fg).attr('stroke-opacity', 0.6)
.call(sel => hook(sel, n => { const p = n.data || n; return `<b>${s.cat}</b><br/>Rebounds per Game: ${nf.format(p.v)}`; }));
});
const ry = y(overallMed);
const ref = g.append('g').style('pointer-events', 'none');
ref.append('line').attr('x1', 0).attr('x2', plotW).attr('y1', ry).attr('y2', ry)
.attr('stroke', fg).attr('stroke-opacity', 0.7).attr('stroke-dasharray', '6 4');
if (!narrow) {
ref.append('text').attr('x', plotW + 6).attr('y', ry - 2).attr('font-size', 11).attr('fill', fg).text('Overall median');
ref.append('text').attr('x', plotW + 6).attr('y', ry + 12).attr('font-size', 11).attr('fill', fg).text(nf.format(overallMed));
} else {
ref.append('text').attr('x', plotW - 2).attr('y', ry - 3).attr('text-anchor', 'end').attr('font-size', 11).attr('fill', fg)
.text('Overall median ' + nf.format(overallMed));
}
const yt = svg.append('text').attr('transform', `translate(14,${margin.top + plotH / 2}) rotate(-90)`)
.attr('text-anchor', 'middle').attr('font-size', 11).attr('fill', fg).text('Rebounds per Game');
d3.llmFitLabel(yt, plotH, { text: 'Rebounds per Game' });
const xTitle = 'Position (by median Rebounds per Game' + (tied ? '; ties by mean)' : ')');
const xt = svg.append('text').attr('x', margin.left + plotW / 2).attr('y', H - 10)
.attr('text-anchor', 'middle').attr('font-size', 11).attr('fill', fg).text(xTitle);
d3.llmFitLabel(xt, W - 16, { text: xTitle });
}Keep going
- What a Violin plot is, and when to use one
- Selection explainer on the same data
- Beeswarm chart on the same data
- Box plot on the same data
- Histogram on the same data
- Parallel coordinates on the same data
- Regression plot (line with CI) on the same data
- Scatter plot on the same data
- Strip plot on the same data
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.