order_value by store_number, as a treemap

How is the order_value split across the store_number values?

2,623 individual orders across 205 stores, each store identified only by an opaque code, with one order value per row. Stores hold anywhere from a single order to 28, and order values are heavily right-skewed: a few very large orders against a much lower median. With that many stores there is no room for a bar per store, so it suits views of the distribution such as a beeswarm, a strip plot or a box plot, and a headline total with the spread behind it.

Order Value by Store, Raw Order Rows: 2623 rows, 2 columns. Download the CSV

The first 10 rows
store_numberorder_value
101YM32484664.31
101YM32481983.54
101YM32482192.7
101YM32481471.61
101YM32482075.21
101YM32483901.92
101YM32481786.24
101YM3248393.05
108JZ815910032.14
108JZ81592520.31
A treemap of the "Order Value by Store, Raw Order Rows" dataset: one rectangle per store_number, sized by its order_value, 205 in all.
A treemap of the "Order Value by Store, Raw Order Rows" dataset: one rectangle per store_number, sized by its order_value, 205 in all.

How to read it

Each rectangle's area is its share of the whole, so compare areas, not positions. 413LT9876 takes the most room, 1.5% of the total.

The chart's code (28 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.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.llmTopN = function (rows, opts) {
opts = opts || {};
var data = Array.isArray(rows) ? rows : [];
var keyOf = typeof opts.key === 'function' ? opts.key : function (r) { return r; };
var valOf = typeof opts.value === 'function' ? opts.value : null;
var groupOf = typeof opts.groupBy === 'function' ? opts.groupBy : null;
var blank = opts.blank != null ? String(opts.blank) : '(blank)';
var nameOf = function (k) { return (k == null || k === '') ? blank : String(k); };

var totals = new Map();
for (var i = 0; i < data.length; i++) {
var m = nameOf(keyOf(data[i], i));
var t = totals.has(m) ? totals.get(m) : 0;
if (valOf) {
var v = valOf(data[i], i);
if (v != null && v !== '' && typeof v !== 'boolean' && isFinite(+v)) t += +v;
} else {
t += 1;
}
totals.set(m, t);
}
var ranked = Array.from(totals.keys()).sort(function (a, b) {
var d = totals.get(b) - totals.get(a);
return d !== 0 ? d : (a < b ? -1 : (a > b ? 1 : 0));
});

var n = Math.floor(+opts.n);
var cap = (isFinite(n) && n >= 1) ? Math.min(n, ranked.length) : ranked.length;
if (ranked.length - cap === 1) cap = ranked.length;
var kept = ranked.slice(0, cap);
var pooled = ranked.slice(cap);
var keptSet = new Set(kept);

var label = (opts.label != null && String(opts.label) !== '') ? String(opts.label) : 'Other';
if (totals.has(label)) label = label + ' (pooled)';

var inGroup = new Map();
if (pooled.length && groupOf) {
for (var j = 0; j < data.length; j++) {
var pm = nameOf(keyOf(data[j], j));
if (keptSet.has(pm)) continue;
var g = nameOf(groupOf(data[j], j));
var s = inGroup.get(g);
if (!s) { s = new Set(); inGroup.set(g, s); }
s.add(pm);
}
}
var drawnAlone = new Set();
var hasPool = false;
if (pooled.length) {
if (!groupOf) hasPool = true;
inGroup.forEach(function (s) {
if (s.size === 1) s.forEach(function (x) { drawnAlone.add(x); });
else if (s.size > 1) hasPool = true;
});
}

var labelOf = function (row, idx) {
var x = nameOf(keyOf(row, idx));
if (!pooled.length || keptSet.has(x)) return x;
if (groupOf) {
var s2 = inGroup.get(nameOf(groupOf(row, idx)));
if (!s2 || s2.size < 2) return x;
}
return label;
};

var order = [];
for (var k = 0; k < ranked.length; k++) {
if (keptSet.has(ranked[k]) || drawnAlone.has(ranked[k])) order.push(ranked[k]);
}
if (hasPool) order.push(label);

return {
kept: kept,
pooled: pooled,
order: order,
label: label,
hasPool: hasPool,
labelOf: labelOf,
isPool: function (x) { return hasPool && String(x) === label; },
membersOf: function (grp) {
if (!pooled.length) return [];
if (!groupOf || grp === undefined) return hasPool ? pooled.slice() : [];
var s3 = inGroup.get(nameOf(grp));
if (!s3 || s3.size < 2) return [];
var out = [];
for (var q = 0; q < pooled.length; q++) if (s3.has(pooled[q])) out.push(pooled[q]);
return out;
},
totalOf: function (x) { return totals.has(nameOf(x)) ? totals.get(nameOf(x)) : 0; }
};
};

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 sIdx = data.columns.findIndex(c => c.name === 'store_number');
  const vIdx = data.columns.findIndex(c => c.name === 'order_value');
  if (sIdx < 0) throw new Error('INVALID:column "store_number" not found');
  if (vIdx < 0) throw new Error('INVALID:column "order_value" not found');
  const items = [];
  data.rows.forEach((r, i) => {
    const v = r[vIdx];
    if (v == null || v === '' || !isFinite(+v) || +v <= 0 || r[sIdx] == null) return;
    items.push({ i, store: String(r[sIdx]), v: +v });
  });
  if (!items.length) { noData(); return; }

  const storeTotals = d3.rollups(items, v => d3.sum(v, d => d.v), d => d.store)
    .map(d => d[1]).sort((a, b) => b - a);
  const nStores = storeTotals.length;
  const grand = d3.sum(storeTotals);
  let N = nStores;
  for (let n = Math.min(12, nStores); n < nStores; n++) {
    const other = grand - d3.sum(storeTotals.slice(0, n));
    if (other <= 0.4 * grand && other <= 2 * storeTotals[0]) { N = n; break; }
  }

  const P = d3.llmTopN(items, { key: r => r.store, value: r => r.v, n: N });
  const agg = new Map();
  items.forEach(it => {
    const lab = P.labelOf(it);
    let a = agg.get(lab);
    if (!a) { a = { name: lab, value: 0, idxs: [], members: new Set() }; agg.set(lab, a); }
    a.value += it.v; a.idxs.push(it.i); a.members.add(it.store);
  });
  const leaves = P.order.filter(l => agg.has(l)).map(l => agg.get(l));
  const total = d3.sum(leaves, d => d.value);
  if (!(total > 0)) { noData(); return; }
  const isOther = d => d.members.size > 1;
  const named = leaves.filter(d => !isOther(d));

  const ext = d3.extent(named.length ? named : leaves, d => d.value);
  const lo = ext[0], hi = ext[1] > ext[0] ? ext[1] : ext[0] + 1;
  const scaleLo = options.colorScaleLow || options.colorScaleAutoLow || d3.interpolateLab('#ffffff', (options.palette && options.palette.length ? options.palette[0] : '#4e79a7'))(0.3);
  const scaleHi = options.colorScaleHigh || options.colorScaleAutoHigh || (options.palette && options.palette.length ? options.palette[0] : '#4e79a7');
  const ramp = d3.interpolateLab(scaleLo, scaleHi);
  const tOf = v => Math.sqrt(Math.max(0, Math.min(1, (v - lo) / (hi - lo))));
  const OTHER_FILL = '#9e9e9e';
  const fillOf = d => isOther(d) ? OTHER_FILL : ramp(tOf(d.value));

  const nf = new Intl.NumberFormat(options.cultureCode, { maximumFractionDigits: 2 });
  const cf = new Intl.NumberFormat(options.cultureCode, { notation: 'compact', maximumSignificantDigits: 3 });
  const pf = new Intl.NumberFormat(options.cultureCode, { style: 'percent', maximumSignificantDigits: 2 });

  const capH = 20, rightW = 120, pad = 6;
  const tw = W - rightW - pad, th = H - capH - pad;
  const capText = (named.length < nStores ? 'Top ' + named.length + ' of ' + nStores : 'All ' + nStores) + ' stores by total order value' + (leaves.length > named.length ? ', rest pooled as Other' : '');
  const cap = svg.append('text').attr('x', pad).attr('y', 14).attr('font-size', 11).attr('fill', fg).text(capText);
  d3.llmFitLabel(cap, W - 2 * pad, { text: capText });

  const root = d3.hierarchy({ children: leaves }).sum(d => d.children ? 0 : d.value);
  d3.treemap().size([tw, th]).paddingInner(2).round(true)(root);
  const g = svg.append('g').attr('transform', `translate(${pad},${capH})`);
  const tip = options.allowTooltips !== false ? d3.llmTooltip(container) : null;

  const leaf = g.selectAll('g.leaf').data(root.leaves()).join('g').attr('class', 'leaf');
  const rects = leaf.append('rect')
    .attr('class', 'd3-mark')
    .attr('data-row-idx', d => d.data.idxs.join(','))
    .attr('x', d => d.x0).attr('y', d => d.y0)
    .attr('width', d => Math.max(0, d.x1 - d.x0)).attr('height', d => Math.max(0, d.y1 - d.y0))
    .attr('fill', d => fillOf(d.data))
    .attr('stroke', options.themeBg || '#fff').attr('stroke-width', 1)
    .style('cursor', 'pointer');
  rects.append('title').text(d => (isOther(d.data) ? d.data.name + ' (' + d.data.members.size + ' stores)' : 'Store ' + d.data.name) + ': ' + nf.format(d.value));
  if (tip) {
    rects.on('mousemove', (event, d) => {
      const nm = isOther(d.data) ? d.data.name + ' (' + d.data.members.size + ' stores)' : 'Store ' + d.data.name;
      tip.show('<b>' + nm + '</b><br/>Total order value: ' + nf.format(d.value) + '<br/>Share of total: ' + pf.format(d.value / total), event);
    }).on('mouseleave', () => tip.hide());
  }
  const labels = leaf.append('text')
    .attr('x', d => (d.x0 + d.x1) / 2).attr('y', d => (d.y0 + d.y1) / 2)
    .attr('text-anchor', 'middle').attr('dominant-baseline', 'middle')
    .attr('font-size', 11)
    .attr('fill', d => d3.lab(fillOf(d.data)).l < 60 ? '#fff' : '#111')
    .style('pointer-events', 'none')
    .text(d => (d.y1 - d.y0) < 14 ? '' : (isOther(d.data) ? d.data.name + ' (' + d.data.members.size + ')' : 'Store ' + d.data.name));
  labels.each(function (d) { if (this.textContent) d3.llmFitLabel(d3.select(this), d.x1 - d.x0 - 4); });

  // colorbar
  const bx = pad + tw + 16, bw = 12, by0 = capH + 42, by1 = H - 24, bh = Math.max(40, by1 - by0);
  const gid = 'tmgrad' + Date.now();
  const defs = svg.append('defs');
  const lg = defs.append('linearGradient').attr('id', gid).attr('x1', 0).attr('x2', 0).attr('y1', 1).attr('y2', 0);
  lg.selectAll('stop').data(d3.range(0, 1.0001, 0.05)).join('stop')
    .attr('offset', t => t).attr('stop-color', t => ramp(Math.sqrt(t)));
  const cb = svg.append('g');
  const t1 = cb.append('text').attr('x', bx - 8).attr('y', capH + 14).attr('font-size', 10).attr('fill', fg).text('Sum of order value');
  d3.llmFitLabel(t1, W - bx + 8 - 4, { text: 'Sum of order value' });
  const t2 = cb.append('text').attr('x', bx - 8).attr('y', capH + 27).attr('font-size', 10).attr('fill', fg).text('(square-root scale)');
  d3.llmFitLabel(t2, W - bx + 8 - 4, { text: '(square-root scale)' });
  cb.append('rect').attr('x', bx).attr('y', by0).attr('width', bw).attr('height', bh)
    .attr('fill', `url(#${gid})`).attr('stroke', fg).attr('stroke-opacity', 0.4).style('pointer-events', 'none');
  [0, 0.25, 0.5, 1].forEach(f => {
    const val = lo + f * (hi - lo);
    const y = by1 - Math.sqrt(f) * bh;
    cb.append('line').attr('x1', bx + bw).attr('x2', bx + bw + 4).attr('y1', y).attr('y2', y).attr('stroke', fg).attr('stroke-opacity', 0.6);
    cb.append('text').attr('x', bx + bw + 7).attr('y', y).attr('dominant-baseline', 'middle').attr('font-size', 10).attr('fill', fg).text(cf.format(val));
  });
}

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 🗙