Sum of Cost by Neighborhood and ComplaintType
Which combinations of Neighborhood and ComplaintType have the most Sum of Cost?
Municipal 311 service requests by complaint type and neighborhood, with days-to-resolve, resolution cost, priority and a same-week-resolved flag. Categorical-heavy with an ordinal priority — a natural fit for ranked bars, heatmaps, and resolution-rate breakdowns.
City 311 Service Complaints: 2800 rows, 7 columns. Download the CSV
| ComplaintID | ComplaintType | Neighborhood | DaysToResolve | Sum of Cost | Priority | ResolvedSameWeek |
|---|---|---|---|---|---|---|
| 311-452754 | Noise | Southside | 17 | 26.7 | Medium | False |
| 311-996178 | Water Main | Downtown | 2 | 85.1 | Low | True |
| 311-435023 | Graffiti | Old Town | 4 | 216.14 | High | True |
| 311-227051 | Illegal Parking | Riverside | 3 | 58.17 | Low | True |
| 311-129421 | Graffiti | Old Town | 3 | 161.06 | High | True |
| 311-712349 | Illegal Parking | Riverside | 40 | 168.77 | Low | False |
| 311-156439 | Water Main | Downtown | 10 | 190.35 | Medium | False |
| 311-587420 | Pothole | Riverside | 4 | 240.43 | Low | True |
| 311-440004 | Illegal Parking | University District | 2 | 248.9 | Low | True |
| 311-930723 | Tree Damage | Riverside | 2 | 212.22 | Low | True |

How to read it
Darker cells hold more Sum of Cost; scan a row or a column for its pattern. Color is good for spotting patterns and less good for exact values, so read the legend for the scale.
The chart's code (33 KB of JavaScript, D3)
It carries its own copies of these helpers: llmText, llmFrameTween, llmRangeBrush, llmSlider, llmNumberEntry, llmSegmented, llmPredictor, llmResponseCurves, llmTerritories, llmCutoff, llmContrast, llmSurvival, llmModelFormat, llmSubgroups, llmSegments, llmGlyphs, llmBreadcrumb, llmKeyframes, llmScrubber, llmValueColumn, llmValueRamp, llmFitLabel, llmThinLabels, llmFitAxisTicks, llmSymlog, llmClipOutliers, llmGeoZoom, llmGeoPointNotes, llmMapLabels, llmGeoMarks, llmPlaceUnit, llmWorldFit, llmRegionFit, llmFlowKey, llmFlowArcs, llmFrameFill, llmTooltip, llmSwarm, llmKde, llmOrbit3d, llmBoundedScale, llmBivariate, llmLegendLayout, llmPager, llmTableFrame, llmGrid, llmUtcDays, llmPeriodGrid, llmTileGrid, llmMermaid, llmDecomp, llmTopN, llmFlipDeck, llmFilterScope, llmDisplayName, llmThemeColors, llmWordCloud.
// bic:keyboard-marks
// English whatever the chart's language. A helper now asks for each one here and declares `// @requires llmText`:
d3.llmText = function (key, english, vars, count) {
var fill = function (s, vv) {
vv = vv || vars;
return String(s).replace(/\{([a-z][a-z0-9_]*)\}/g, function (m, k) {
return vv && Object.prototype.hasOwnProperty.call(vv, k) ? String(vv[k]) : m;
});
};
var en = fill(english);
var host = d3.llmText.host;
if (typeof host === 'function') {
try { var h = host(key, english, vars, count); if (typeof h === 'string' && h !== en && h !== english) return h; } catch (e) {}
}
var cat = d3.llmText._cat, lang = d3.llmText._lang;
if (cat && lang && Object.prototype.hasOwnProperty.call(cat, key)) {
var v = cat[key];
if (v && typeof v === 'object') {
var form = 'other';
try { form = new Intl.PluralRules(lang).select(typeof count === 'number' ? count : 0); } catch (e) {}
v = v[form] != null ? v[form] : v.other != null ? v.other : v.many;
}
var tv = vars;
if (vars && typeof vars.grain === 'string' && Object.prototype.hasOwnProperty.call(cat, 'd3.grain.' + vars.grain)
&& typeof cat['d3.grain.' + vars.grain] === 'string' && cat['d3.grain.' + vars.grain]) {
tv = {};
for (var vk in vars) if (Object.prototype.hasOwnProperty.call(vars, vk)) tv[vk] = vars[vk];
tv.grain = cat['d3.grain.' + vars.grain];
}
if (typeof v === 'string' && v) {
var t = fill(v, tv), left = String(t).match(/\{[a-z][a-z0-9_]*\}/g) || [];
if (left.every(function (x) { return en.indexOf(x) >= 0; })) return t;
}
}
return en;
};
d3.llmText._lang = null;
d3.llmText._cat = null;
d3.llmText.use = function (lang, catalog) {
d3.llmText._lang = lang || null; d3.llmText._cat = catalog || null;
d3.llmText.dates(lang);
};
d3.llmText.dates = function (lang) {
try {
var o = d3.llmText._d3orig;
if (!o) {
o = d3.llmText._d3orig = { timeFormat: d3.timeFormat, utcFormat: d3.utcFormat, timeParse: d3.timeParse,
utcParse: d3.utcParse, scaleTime: d3.scaleTime, scaleUtc: d3.scaleUtc };
}
var restore = function () { for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k) && o[k]) d3[k] = o[k]; };
var base = String(lang || '').toLowerCase().split(/[-_]/)[0];
if (!base || base === 'en' || typeof d3.timeFormatLocale !== 'function' || typeof Intl === 'undefined') { restore(); return; }
var mk = function (opts) { var x = { timeZone: 'UTC' }; for (var k in opts) x[k] = opts[k]; return new Intl.DateTimeFormat(lang, x); };
var months = [], shortMonths = [], days = [], shortDays = [], m, w;
var fM = mk({ month: 'long' }), fMs = mk({ month: 'short' }), fD = mk({ weekday: 'long' }), fDs = mk({ weekday: 'short' });
for (m = 0; m < 12; m++) { var dm = new Date(Date.UTC(2021, m, 15)); months.push(fM.format(dm)); shortMonths.push(fMs.format(dm)); }
for (w = 0; w < 7; w++) { var dw = new Date(Date.UTC(2021, 0, 3 + w)); days.push(fD.format(dw)); shortDays.push(fDs.format(dw)); } // 3 Jan 2021 is a Sunday
if (months[0] === 'January' && days[0] === 'Sunday') { restore(); return; } // no names for the language here: keep d3's
var L = d3.timeFormatLocale({ dateTime: '%x %X', date: '%Y-%m-%d', time: '%H:%M:%S', periods: ['AM', 'PM'],
days: days, shortDays: shortDays, months: months, shortMonths: shortMonths });
d3.timeFormat = L.format; d3.utcFormat = L.utcFormat; d3.timeParse = L.parse; d3.utcParse = L.utcParse;
var multi = function (utc) {
var F = utc ? L.utcFormat : L.format, P = utc ? 'utc' : 'time';
var iv = function (n) { return d3[P + n]; };
var fL = F('.%L'), fS = F(':%S'), fMi = F('%H:%M'), fH = F('%H:00'), fDy = F('%a %d'), fW = F('%b %d'), fMo = F('%B'), fY = F('%Y');
var wk = utc ? d3.utcSunday : d3.timeSunday;
return function (date) {
return (iv('Second')(date) < date ? fL : iv('Minute')(date) < date ? fS : iv('Hour')(date) < date ? fMi
: iv('Day')(date) < date ? fH : iv('Month')(date) < date ? (wk(date) < date ? fDy : fW)
: iv('Year')(date) < date ? fMo : fY)(date);
};
};
var wrap = function (make, utc) {
if (typeof make !== 'function') return make;
var dress = function (sc) {
var cp = sc.copy;
sc.tickFormat = function (count, spec) { return spec == null ? multi(utc) : (utc ? L.utcFormat : L.format)(spec); };
if (typeof cp === 'function') sc.copy = function () { return dress(cp.apply(sc, arguments)); };
return sc;
};
return function () { return dress(make.apply(this, arguments)); };
};
d3.scaleTime = wrap(o.scaleTime, false); d3.scaleUtc = wrap(o.scaleUtc, true);
} catch (e) {}
};
// @requires llmFilterScope
d3.llmValueRamp = function (cfg) {
var TYPE_FLOOR = 10; // the minimum readable type, px: the legend's labels draw no smaller
cfg = cfg || {};
var num = function (v) { return (v == null || v === '' || !isFinite(+v)) ? null : +v; };
var vals = [];
(cfg.values || []).forEach(function (v) { v = num(v); if (v != null) vals.push(v); });
vals.sort(function (a, b) { return a - b; });
var mid = num(cfg.mid), diverging = mid != null;
var asColour = function (c) {
if (c && typeof c === 'object' && typeof c.formatHex === 'function') return c;
return typeof c === 'string' && c.trim() !== '' && num(c) == null && d3.color(c) ? c : null;
};
var boundLo = asColour(cfg.low) ? null : num(cfg.low), boundHi = asColour(cfg.high) ? null : num(cfg.high);
var low = asColour(cfg.low) || (diverging ? '#b35806' : '#eef3f8'), high = asColour(cfg.high) || (diverging ? '#2166ac' : '#3182bd');
var cvColor = cfg.canvas ? d3.color(cfg.canvas) : null;
var lumOf = function (c) {
var q = d3.rgb(c);
var f = function (u) { u /= 255; return u <= 0.03928 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4); };
return 0.2126 * f(q.r) + 0.7152 * f(q.g) + 0.0722 * f(q.b);
};
var onPage = function (c) { var a = lumOf(c), b = lumOf(cvColor); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); };
var darkCanvas = !!(cvColor && !cfg.highContrast && cvColor.opacity >= 1 && lumOf(cvColor) < 0.2);
var offPage = function (c, floor) {
var q = d3.lab(c);
if (!isFinite(q.l)) return c;
for (var i = 0; i < 60 && q.l < 100 && onPage(q.formatHex()) < floor; i++) q.l = Math.min(100, q.l + 2);
return q.formatHex();
};
if (darkCanvas && !diverging) {
var toHigh = d3.interpolateLab(low, high), s = 0;
while (s < 20 && onPage(d3.lab(toHigh(s / 20)).formatHex()) < 3) s++;
low = offPage(d3.lab(toHigh(s / 20)).formatHex(), 3);
high = offPage(high, Math.max(3, onPage(low) * 2));
}
var midColor = cfg.midColor;
if (!midColor) {
var cv = cfg.canvas ? d3.lab(cfg.canvas) : null, cl = cv && isFinite(cv.l) ? cv.l : null;
if (cl == null && !cfg.highContrast) midColor = '#f7f7f7';
else {
if (cl == null) cl = 100;
var off = cfg.highContrast ? 25 : (cl < 50 ? 18 : 3);
midColor = d3.lab(cl < 50 ? cl + off : cl - off, 0, 0).formatHex();
}
}
var n = vals.length;
var lo = n ? vals[0] : 0, hi = n ? vals[n - 1] : 1;
if (boundLo != null && (!n || boundLo < lo)) lo = boundLo; // a numeric low / high widens the range, never narrows it
if (boundHi != null && (!n || boundHi > hi)) hi = boundHi;
var median = n ? d3.quantile(vals, 0.5) : null, p95 = n ? d3.quantile(vals, 0.95) : null;
var scale = d3.scaleLinear().domain(lo === hi ? [lo - 1, hi] : [lo, hi]).range([low, high]).clamp(true);
var kind = n && lo === hi ? 'constant' : 'linear', edges = [lo, hi], colors = [low, high];
if (diverging) {
var span = Math.max(Math.abs(lo - mid), Math.abs(hi - mid)) || Math.abs(mid) || 1;
edges = [mid - span, mid, mid + span];
colors = [low, midColor, high];
scale = d3.scaleLinear().domain(edges).range([low, midColor, high]).clamp(true);
kind = 'diverging';
} else if (n >= 10 && lo >= 0 && lo !== hi && p95 > 4 * median) {
var inner = [];
for (var q = 1; q < 5; q++) {
var t = vals[Math.floor(q * n / 5)];
if (t > lo && (!inner.length || t > inner[inner.length - 1])) inner.push(t);
}
if (inner.length >= 2) {
var along = d3.scaleLinear().domain([0, inner.length]).range([low, high]);
colors = [];
for (var c = 0; c <= inner.length; c++) colors.push(along(c));
scale = function (v) { return colors[d3.bisectRight(inner, v)]; };
edges = [lo].concat(inner, [hi]);
kind = 'bands';
}
}
var atCentre = function (v) { return kind === 'diverging' && Math.abs(v - mid) <= 1e-9 * Math.max(1, Math.abs(mid)); };
var drawVertical = function (g, w, h, size, fg, op, fmt, o) {
var fs = Math.max(TYPE_FLOOR, size); // floored here too: the caller's size arrives as a parameter
var lx = w + 4, rows = [], widest = 0, k = colors.length;
var a0 = kind === 'diverging' ? edges[0] : lo, a1 = kind === 'diverging' ? edges[edges.length - 1] : hi;
var at = function (f) { return h - Math.max(0, Math.min(1, f)) * h; }; // 0 = the low end, 1 = the high end
var frac = function (v) {
if (kind === 'bands') {
var bi = Math.max(0, Math.min(k - 1, d3.bisectRight(edges, v) - 1));
var sp = edges[bi + 1] - edges[bi];
return (bi + (sp > 0 ? Math.max(0, Math.min(1, (v - edges[bi]) / sp)) : 0)) / k;
}
return a1 > a0 ? (v - a0) / (a1 - a0) : 0.5;
};
var placeY = function (y, text, always, cls) {
var y0 = y - 0.8 * fs, y1 = y + 0.2 * fs;
if (!always && rows.some(function (r) { return y0 < r[1] + 4 && y1 > r[0] - 4; })) return false;
rows.push([y0, y1]);
g.append('text').attr('class', cls || 'llm-value-ramp-label').attr('x', lx).attr('y', y)
.attr('text-anchor', 'start').attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
widest = Math.max(widest, String(text).length * fs * 0.58);
return true;
};
var box = function () {
var bottom = h;
rows.forEach(function (r) { bottom = Math.max(bottom, r[1]); });
return { width: lx + widest, height: bottom };
};
if (kind === 'bands') {
var sh = h / k;
for (var b = 0; b < k; b++) {
var r = g.append('rect').attr('class', 'llm-value-ramp-band').attr('y', (k - 1 - b) * sh).attr('width', w)
.attr('height', sh).attr('fill', colors[b]).attr('data-from', edges[b]).attr('data-to', edges[b + 1]);
if (o.stroke) r.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
} else {
var id = o.id || ('llmramp-' + Math.abs((w * 131 + h * 7) | 0) + '-v' + (kind === 'diverging' ? 'd' : ''));
var lg = g.append('defs').append('linearGradient').attr('id', id)
.attr('x1', '0%').attr('y1', '100%').attr('x2', '0%').attr('y2', '0%');
lg.append('stop').attr('offset', '0%').attr('stop-color', low);
if (kind === 'diverging') lg.append('stop').attr('offset', '50%').attr('stop-color', midColor);
lg.append('stop').attr('offset', '100%').attr('stop-color', high);
var bar = g.append('rect').attr('class', 'llm-value-ramp-bar').attr('width', w).attr('height', h)
.attr('fill', 'url(#' + id + ')');
if (o.stroke) bar.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
if (kind === 'constant') {
placeY(Math.min(h, 0.8 * fs), fmt(lo) + (o.constantText || ''), true);
return box();
}
var topY = 0.8 * fs, botY = Math.max(h, topY + fs + 4);
placeY(topY, fmt(a1), true);
placeY(botY, fmt(a0), true);
if (o.highLabel) placeY(topY + fs + 2, o.highLabel, true, 'llm-value-ramp-side');
if (o.lowLabel) placeY(botY + fs + 2, o.lowLabel, true, 'llm-value-ramp-side');
if (kind === 'diverging') {
var cy = at(0.5);
var cl = g.append('line').attr('class', 'llm-value-ramp-mid').attr('x1', 0).attr('x2', w)
.attr('y1', cy).attr('y2', cy).attr('stroke', fg).attr('stroke-opacity', 0.6).attr('stroke-width', 1);
if (!placeY(cy + 0.3 * fs, fmt(mid), false)) cl.append('title').text(fmt(mid));
}
(o.marks || []).forEach(function (m) {
var v = num(m && m.value);
if (v == null || atCentre(v)) return;
var y = at(frac(v));
var text = (m.label != null && m.label !== '' ? m.label + ' ' : '') + fmt(v);
var tick = g.append('line').attr('class', 'llm-value-ramp-mark').attr('x1', -2).attr('x2', w + 2)
.attr('y1', y).attr('y2', y).attr('stroke', fg).attr('stroke-width', 1.5).attr('stroke-dasharray', '3,2');
if (!placeY(y + 0.3 * fs, text, false)) tick.append('title').text(text);
});
if (kind === 'bands') for (var e = 1; e < k; e++) placeY(at(e / k) + 0.3 * fs, fmt(edges[e]), false);
return box();
};
var drawLegend = function (parent, o) {
o = o || {};
var vertical = o.orient === 'vertical' ||
(o.orient !== 'horizontal' && +o.width > 0 && +o.height > 2 * +o.width);
var w = o.width || (vertical ? 12 : 120), h = o.height || (vertical ? 120 : 8), fs = Math.max(TYPE_FLOOR, o.fontSize || TYPE_FLOOR);
var fg = o.fg || '#333', op = o.fgOpacity == null ? 1 : o.fgOpacity;
var ly = o.labelY == null ? h + fs : o.labelY;
var fmt = typeof o.format === 'function' ? o.format : function (v) { return String(v); };
var g = parent.append('g').attr('class', 'llm-value-ramp').attr('data-kind', kind)
.attr('transform', 'translate(' + (o.x || 0) + ',' + (o.y || 0) + ')');
if (vertical) {
g.attr('data-orient', 'vertical');
return drawVertical(g, w, h, fs, fg, op, fmt, o);
}
var label = function (x, anchor, text) {
g.append('text').attr('class', 'llm-value-ramp-label').attr('x', x).attr('y', ly)
.attr('text-anchor', anchor).attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
};
var taken = [];
var place = function (x, anchor, text, always) {
var wd = String(text).length * fs * 0.58;
var x0 = anchor === 'start' ? x : anchor === 'end' ? x - wd : x - wd / 2;
if (!always && taken.some(function (s) { return x0 < s[1] + 4 && x0 + wd > s[0] - 4; })) return false;
taken.push([x0, x0 + wd]);
label(x, anchor, text);
return true;
};
var k = colors.length, sw = w / k;
var a0 = kind === 'diverging' ? edges[0] : lo, a1 = kind === 'diverging' ? edges[edges.length - 1] : hi;
if (kind !== 'bands') {
var id = o.id || ('llmramp-' + Math.abs((w * 131 + h * 7) | 0) + (kind === 'diverging' ? '-d' : ''));
var lg = g.append('defs').append('linearGradient').attr('id', id);
lg.append('stop').attr('offset', '0%').attr('stop-color', low);
if (kind === 'diverging') lg.append('stop').attr('offset', '50%').attr('stop-color', midColor);
lg.append('stop').attr('offset', '100%').attr('stop-color', high);
var bar = g.append('rect').attr('class', 'llm-value-ramp-bar').attr('width', w).attr('height', h)
.attr('fill', 'url(#' + id + ')');
if (o.stroke) bar.attr('stroke', o.stroke).attr('stroke-width', 0.5);
if (kind === 'constant') {
label(0, 'start', fmt(lo) + (o.constantText || ''));
return { width: w, height: Math.max(h, ly) };
}
place(0, 'start', fmt(a0), true);
place(w, 'end', fmt(a1), true);
if (kind === 'diverging') {
var cl = g.append('line').attr('class', 'llm-value-ramp-mid').attr('x1', w / 2).attr('x2', w / 2)
.attr('y1', 0).attr('y2', h).attr('stroke', fg).attr('stroke-opacity', 0.6).attr('stroke-width', 1);
if (!place(w / 2, 'middle', fmt(mid), false)) cl.append('title').text(fmt(mid));
}
} else {
for (var b = 0; b < k; b++) {
var r = g.append('rect').attr('class', 'llm-value-ramp-band').attr('x', b * sw).attr('width', sw)
.attr('height', h).attr('fill', colors[b]).attr('data-from', edges[b]).attr('data-to', edges[b + 1]);
if (o.stroke) r.attr('stroke', o.stroke).attr('stroke-width', 0.5);
}
place(0, 'start', fmt(lo), true);
place(w, 'end', fmt(hi), true);
}
(o.marks || []).forEach(function (m) {
var v = num(m && m.value);
if (v == null || atCentre(v)) return;
var x;
if (kind === 'bands') {
var bi = Math.max(0, Math.min(k - 1, d3.bisectRight(edges, v) - 1));
var span = edges[bi + 1] - edges[bi];
x = (bi + (span > 0 ? Math.max(0, Math.min(1, (v - edges[bi]) / span)) : 0)) * sw;
} else {
x = Math.max(0, Math.min(w, (v - a0) / (a1 - a0) * w));
}
var text = (m.label != null && m.label !== '' ? m.label + ' ' : '') + fmt(v);
var tick = g.append('line').attr('class', 'llm-value-ramp-mark').attr('x1', x).attr('x2', x)
.attr('y1', -2).attr('y2', h + 2).attr('stroke', fg).attr('stroke-width', 1.5)
.attr('stroke-dasharray', '3,2');
if (!place(x, 'middle', text, false)) tick.append('title').text(text);
});
if (kind === 'bands') for (var e = 1; e < k; e++) place(e * sw, 'middle', fmt(edges[e]), false);
var bottom = ly;
if (o.lowLabel || o.highLabel) {
var sy = ly + fs + 2, lwd = o.lowLabel ? String(o.lowLabel).length * fs * 0.58 : 0;
var hwd = o.highLabel ? String(o.highLabel).length * fs * 0.58 : 0;
var side = function (x, anchor, text) {
g.append('text').attr('class', 'llm-value-ramp-side').attr('x', x).attr('y', sy)
.attr('text-anchor', anchor).attr('font-size', fs).attr('fill', fg).attr('fill-opacity', op).text(text);
};
if (o.lowLabel) side(0, 'start', o.lowLabel);
if (o.highLabel) { if (lwd + hwd + 8 > w) side(lwd ? lwd + 8 : 0, 'start', o.highLabel); else side(w, 'end', o.highLabel); }
bottom = sy;
}
return { width: w, height: Math.max(h, bottom) };
};
var colorOf = function (v) { v = num(v); return v == null ? null : scale(v); };
var relLum = function (c) {
var q = c ? d3.color(c) : null;
if (!q) return null;
q = q.rgb();
var f = function (u) { u /= 255; return u <= 0.03928 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4); };
var L = 0.2126 * f(q.r) + 0.7152 * f(q.g) + 0.0722 * f(q.b);
return isFinite(L) ? L : null;
};
var ink = function (v, a, b) {
var lf = relLum(colorOf(v)), la = relLum(a), lb = relLum(b);
if (lf == null || la == null || lb == null) return a;
var ratio = function (x, y) { return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
return ratio(lf, la) >= ratio(lf, lb) ? a : b;
};
var self = {
color: colorOf, ink: ink,
kind: kind, skewed: kind === 'bands', lo: lo, hi: hi, median: median, p95: p95, mid: diverging ? mid : null,
edges: edges, colors: colors, drawLegend: drawLegend,
landFill: function (c) {
if (!darkCanvas) return c || '#e6e6e6';
return offPage(c || d3.lab(d3.lab(cvColor).l, 0, 0).formatHex(), 3);
},
onCanvas: function (o) {
var canvas = o, hc = false, next = null;
if (o && typeof o === 'object') {
canvas = o.backgroundColor && o.backgroundColor !== 'transparent' ? o.backgroundColor : o.themeBg;
hc = !!o.isHighContrast;
var scope = d3.llmFilterScope(o);
var kept = scope.domain('llmValueRamp:' + (cfg.key == null ? '' : String(cfg.key)), cfg.values || []);
if (scope.narrowed && kept.cohort === 'all') next = { values: kept.values };
}
if (canvas && !cfg.canvas) next = Object.assign(next || {}, { canvas: canvas, highContrast: hc });
return next ? d3.llmValueRamp(Object.assign({}, cfg, next)) : self;
},
};
return self;
};
d3.llmTooltip = function (container, opts) {
opts = opts || {};
var gap = opts.gap == null ? 12 : opts.gap; // distance from the cursor
var edge = opts.edge == null ? 4 : opts.edge; // minimum distance from the container edge
var routed = false; // true while the HOST is showing our content
var lastContent = ''; // what to re-send if the host is driving
var lastEv = null; // where the cursor last was, for a re-fit
var host = (container && typeof container.node === 'function') ? container.node() : container;
var noop = { show: function () { return this; }, move: function () { return this; }, hide: function () { return this; },
html: function () { return this; }, text: function () { return this; }, node: null };
if (!host || !host.appendChild) return noop;
var mount = host;
if (mount.tagName && String(mount.tagName).toLowerCase() === 'svg' && mount.parentNode) {
mount = mount.parentNode;
}
if (!mount || !mount.appendChild) return noop;
try {
var pos = (typeof getComputedStyle === 'function') ? getComputedStyle(mount).position : '';
if (!pos || pos === 'static') mount.style.position = 'relative';
} catch (e) { /* jsdom / exec-gate: no layout engine, positioning is inert anyway */ }
var tip = mount.__llmTip;
if (!tip || tip.parentNode !== mount) {
tip = document.createElement('div');
tip.className = 'llm-tooltip';
tip.style.position = 'absolute';
tip.style.left = '0px';
tip.style.top = '0px';
tip.style.pointerEvents = 'none';
tip.style.visibility = 'hidden';
tip.style.zIndex = '20';
tip.style.boxSizing = 'border-box';
tip.style.whiteSpace = opts.wrap ? 'normal' : 'nowrap';
tip.style.background = 'rgba(255,255,255,0.97)';
tip.style.border = '1px solid rgba(0,0,0,0.28)';
tip.style.borderRadius = '4px';
tip.style.padding = '6px 9px';
tip.style.boxShadow = '0 2px 6px rgba(0,0,0,0.22)';
tip.style.color = '#222';
tip.style.fontSize = '12px';
mount.appendChild(tip);
mount.__llmTip = tip;
}
function hostTip() {
try {
var n = mount, guard = 0;
while (n && guard++ < 8) {
if (n.__lchHostTip && typeof n.__lchHostTip.show === 'function') return n.__lchHostTip;
n = n.parentNode;
}
} catch (e) { /* detached node / cross-document parent */ }
return null;
}
function metrics() {
var w = 0, h = 0, cw = 0, ch = 0;
try {
var r = mount.getBoundingClientRect();
cw = r.width; ch = r.height;
} catch (e) { /* fall through to the client* fallbacks */ }
if (!cw) cw = mount.clientWidth || 0;
if (!ch) ch = mount.clientHeight || 0;
w = tip.offsetWidth || 0;
h = tip.offsetHeight || 0;
return { w: w, h: h, cw: cw, ch: ch };
}
function local(ev) {
var x = 0, y = 0;
try {
var r = mount.getBoundingClientRect();
if (ev && ev.clientX != null) { x = ev.clientX - r.left; y = ev.clientY - r.top; }
} catch (e) {
if (ev && ev.clientX != null) { x = ev.clientX; y = ev.clientY; }
}
return { x: x, y: y };
}
function place(ev) {
var m = metrics();
if (!m.cw || !m.ch) return; // no layout to clamp against (exec gate)
var p = local(ev);
var left = p.x + gap;
if (left + m.w > m.cw - edge) left = p.x - gap - m.w;
if (left < edge) left = edge;
if (left + m.w > m.cw - edge) left = Math.max(edge, m.cw - m.w - edge);
var top = p.y + gap;
if (top + m.h > m.ch - edge) top = p.y - gap - m.h;
if (top < edge) top = edge;
if (top + m.h > m.ch - edge) top = Math.max(edge, m.ch - m.h - edge);
tip.style.left = Math.round(left) + 'px';
tip.style.top = Math.round(top) + 'px';
}
function looksLikeEvent(x) {
return !!x && typeof x === 'object' && !Array.isArray(x)
&& (typeof x.clientX === 'number' || typeof x.type === 'string' || ('target' in x));
}
function setContent(content, asText) {
if (Array.isArray(content)) content = content.map(function (x) { return x == null ? '' : String(x); }).join(asText ? ' ' : '<br/>');
lastContent = content == null ? '' : String(content);
if (!asText && typeof content === 'string' && content.indexOf('<') >= 0) tip.innerHTML = lastContent;
else tip.textContent = lastContent;
}
function setAndRefit(self, content, asText) {
setContent(content, asText);
if (routed) {
var hbSet = hostTip();
if (hbSet && hbSet.show(lastContent, lastEv) === true) return self;
routed = false; // the host let go: the tooltip is still on screen, so draw ours
return self.show(null, lastEv);
}
if (tip.style.visibility === 'visible') return self.show(null, lastEv);
return self;
}
return {
node: tip,
html: function (content) { return arguments.length ? setAndRefit(this, content, false) : lastContent; },
text: function (content) { return arguments.length ? setAndRefit(this, content, true) : (tip.textContent || ''); },
show: function (content, ev) {
if (looksLikeEvent(content) && !looksLikeEvent(ev)) { var swapped = content; content = ev; ev = swapped; }
if (ev) lastEv = ev;
if (content != null) setContent(content, false);
tip.style.maxWidth = 'none';
tip.style.visibility = 'visible'; // measurable BEFORE placing
var m = metrics();
if (m.ch && m.h + (2 * edge) > m.ch) {
var hbShow = hostTip();
if (hbShow && hbShow.show(lastContent, ev) === true) {
routed = true;
tip.style.visibility = 'hidden';
return this;
}
}
routed = false;
if (m.cw) tip.style.maxWidth = Math.max(80, m.cw - (2 * edge)) + 'px';
place(ev);
return this;
},
move: function (ev) {
if (ev) lastEv = ev;
if (routed) { var hbMove = hostTip(); if (hbMove) hbMove.move(ev); return this; }
if (tip.style.visibility === 'visible') place(ev);
return this;
},
hide: function () {
if (routed) { var hbHide = hostTip(); if (hbHide) hbHide.hide(); routed = false; }
tip.style.visibility = 'hidden';
return this;
}
};
};
// @requires llmText
d3.llmFilterScope = function (options) {
var f = options && options.filterScope;
var vals = [];
if (f && typeof f === 'object' && f.values && typeof f.values.length === 'number' && typeof f.values !== 'string') {
for (var i = 0; i < f.values.length; i++) {
var v = f.values[i];
if (v !== null && v !== undefined && String(v).trim() !== '' && vals.indexOf(String(v)) < 0) vals.push(String(v));
}
}
var label = '';
if (f && typeof f === 'object' && typeof f.label === 'string' && f.label.trim()) label = f.label.trim();
else if (vals.length === 1) label = d3.llmText('d3.filterscope.only', '{value} only', { value: vals[0] });
else if (vals.length === 2) label = d3.llmText('d3.segments.and', '{first} and {second}', { first: vals[0], second: vals[1] });
else if (vals.length > 2) label = d3.llmText('d3.filterscope.and_more', '{first} and {count} more', { first: vals[0], count: vals.length - 1 }, vals.length - 1);
var narrowed = label !== '';
return {
narrowed: narrowed,
label: label,
field: f && typeof f === 'object' && typeof f.field === 'string' ? f.field : '',
values: vals,
title: function (name) { return narrowed ? String(name) + ' \u00b7 ' + label : String(name); },
baseline: function (key, compute) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = String(key);
if (!narrowed) {
var v = typeof compute === 'function' ? compute() : compute;
if (typeof v === 'number' && isFinite(v)) mem[k] = v;
return { value: v, cohort: 'all' };
}
if (Object.prototype.hasOwnProperty.call(mem, k)) return { value: mem[k], cohort: 'all' };
return { value: typeof compute === 'function' ? compute() : compute, cohort: 'shown' };
},
domain: function (key, values) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = 'domain:' + String(key), shown = [];
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n !== null && n !== undefined && n !== '' && typeof n !== 'boolean' && isFinite(+n)) shown.push(+n);
}
var out = function (v, cohort) {
var lo = null, hi = null;
for (var j = 0; j < v.length; j++) { if (lo === null || v[j] < lo) lo = v[j]; if (hi === null || v[j] > hi) hi = v[j]; }
return { values: v, lo: lo, hi: hi, cohort: cohort };
};
if (!narrowed) {
if (shown.length) mem[k] = shown.slice();
return out(shown, 'all');
}
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null;
if (kept && typeof kept.length === 'number' && kept.length) {
var full = out(kept, 'all'), wide = kept.slice();
for (var w = 0; w < shown.length; w++) if (shown[w] < full.lo || shown[w] > full.hi) wide.push(shown[w]);
return out(wide, 'all');
}
return out(shown, 'shown');
},
track: function (key, kind, values, reference) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var kd = kind === 'span' || kind === 'range' ? kind : 'top';
var k = 'track:' + kd + ':' + String(key), ref = +reference, lo = null, hi = null, wide = null;
if (kd === 'span' && !isFinite(ref)) ref = 0;
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n === null || n === undefined || n === '' || typeof n === 'boolean' || !isFinite(+n)) continue;
n = kd === 'span' ? Math.abs(+n - ref) : +n;
if (lo === null || n < lo) lo = n;
if (hi === null || n > hi) hi = n;
}
var shown = kd === 'range' ? (lo === null ? null : [lo, hi]) : (hi || 1);
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null, cohort = 'all', widened = false;
if (!narrowed) {
if (shown !== null) mem[k] = kd === 'range' ? shown.slice() : shown;
wide = shown;
} else if (kd === 'range' ? kept && kept.length === 2 : typeof kept === 'number' && isFinite(kept)) {
if (kd === 'range') {
wide = kept.slice();
if (shown !== null && shown[0] < wide[0]) { wide[0] = shown[0]; widened = true; }
if (shown !== null && shown[1] > wide[1]) { wide[1] = shown[1]; widened = true; }
} else {
wide = kept;
if (shown > kept) { wide = shown; widened = true; }
}
} else {
wide = shown;
cohort = 'shown';
}
if (kd === 'top') return { domain: [0, wide], lo: 0, hi: wide, value: wide, cohort: cohort, widened: widened };
if (kd === 'span') return { domain: [-wide, wide], lo: -wide, hi: wide, value: wide, cohort: cohort, widened: widened };
if (wide === null) return { domain: [0, 1], lo: null, hi: null, value: null, cohort: cohort, widened: widened };
var pad = wide[1] > wide[0] ? 0 : (Math.abs(wide[0]) * 0.01 || 0.01);
return { domain: [wide[0] - pad, wide[1] + pad], lo: wide[0], hi: wide[1], value: null, cohort: cohort, widened: widened };
},
among: function (text) { return narrowed ? String(text) + ' (' + label + ')' : String(text); }
};
};
d3.llmFilterScope.reference = function (field, values) {
var w = String(field == null ? '' : field).replace(/YoY|MoM|QoQ|WoW/g, function (m) { return ' ' + m.toLowerCase() + ' '; })
.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ');
if (/\b(growth|yoy|mom|qoq|wow|change|gap|variance|delta)\b/i.test(w)) return { value: 0, kind: 'zero' };
if (!/\b(attainment|achievement|of (target|plan|quota|budget|goal)|vs\.? (target|plan|quota|budget|goal)|to (target|plan|quota|goal))\b/i.test(w)) return null;
var v = [];
for (var i = 0; values && i < values.length; i++) { var n = values[i]; if (n !== null && n !== undefined && n !== '' && isFinite(+n)) v.push(+n); }
for (var k = 0; k < v.length; k++) if (v[k] < 0) return { value: 0, kind: 'zero' };
v.sort(function (a, b) { return a - b; });
var md = v.length ? (v.length % 2 ? v[(v.length - 1) / 2] : (v[v.length / 2 - 1] + v[v.length / 2]) / 2) : 1;
return { value: md < 10 ? 1 : 100, kind: 'goal' };
};
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 cols = data.columns.map(c => c.name);
const xi = cols.indexOf('Neighborhood'), yi = cols.indexOf('ComplaintType'), vi = cols.indexOf('Sum of Cost');
const ri = cols.indexOf('__rowIdx__');
if (xi < 0) throw new Error('INVALID:column "Neighborhood" not found');
if (yi < 0) throw new Error('INVALID:column "ComplaintType" not found');
if (vi < 0) throw new Error('INVALID:column "Sum of Cost" not found');
const cells = new Map();
data.rows.forEach((r, i) => {
const v = r[vi];
if (v == null || v === '' || !isFinite(+v)) return;
const x = String(r[xi]), y = String(r[yi]);
const k = x + '\u0001' + y;
let c = cells.get(k);
if (!c) { c = { x, y, sum: 0, idx: [] }; cells.set(k, c); }
c.sum += +v;
c.idx.push(ri >= 0 ? r.__rowIdx__ !== undefined ? r.__rowIdx__ : data.rows[i][ri] : i);
});
const cellArr = [...cells.values()];
if (!cellArr.length) {
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');
return;
}
const order = key => d3.rollups(cellArr, v => d3.sum(v, d => d.sum), d => d[key]).sort((a, b) => d3.descending(a[1], b[1])).map(d => d[0]);
const xs = order('x'), ys = order('y');
const idxBy = key => { const m = new Map(); cellArr.forEach(c => { if (!m.has(c[key])) m.set(c[key], []); m.get(c[key]).push(...c.idx); }); return m; };
const xIdx = idxBy('x'), yIdx = idxBy('y');
const nf = new Intl.NumberFormat(options.cultureCode, { maximumFractionDigits: 2 });
const cf = new Intl.NumberFormat(options.cultureCode, { notation: 'compact', maximumSignificantDigits: 3 });
const fs = 11;
const maxY = d3.max(ys, s => s.length) || 8;
const margin = { top: 12, right: 100, bottom: 110, left: Math.min(W * 0.3, maxY * 6.2 + 42) };
const pw = W - margin.left - margin.right, ph = H - margin.top - margin.bottom;
const x = d3.scaleBand().domain(xs).range([0, pw]).padding(0.04);
const y = d3.scaleBand().domain(ys).range([0, ph]).padding(0.04);
const scope = d3.llmFilterScope(options);
const sums = cellArr.map(c => c.sum);
const k = scope.domain('Sum of Cost', sums);
const ramp = d3.llmValueRamp({
values: [k.lo, k.hi],
low: options.colorScaleLow || options.colorScaleAutoLow,
high: options.colorScaleHigh || options.colorScaleAutoHigh
}).onCanvas(options);
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
const tip = options.allowTooltips !== false ? d3.llmTooltip(container) : null;
const showLabels = x.bandwidth() >= 40 && y.bandwidth() >= 22;
const fills = new Map(cellArr.map(c => [c, ramp.color(c.sum)]));
const cg = g.selectAll('rect.d3-mark').data(cellArr).join('rect')
.attr('class', 'd3-mark')
.attr('data-row-idx', d => d.idx.join(','))
.attr('x', d => x(d.x)).attr('y', d => y(d.y))
.attr('width', x.bandwidth()).attr('height', y.bandwidth())
.attr('fill', d => fills.get(d))
.style('cursor', 'pointer');
if (tip) {
cg.on('mousemove', (event, d) => tip.show(`<b>${d.y} / ${d.x}</b><br/>Sum of Cost: ${nf.format(d.sum)}<br/>Complaints: ${d.idx.length}`, event))
.on('mouseleave', () => tip.hide());
}
if (showLabels) {
g.selectAll('text.cell-label').data(cellArr).join('text')
.attr('class', 'cell-label')
.attr('x', d => x(d.x) + x.bandwidth() / 2).attr('y', d => y(d.y) + y.bandwidth() / 2)
.attr('text-anchor', 'middle').attr('dominant-baseline', 'central')
.attr('font-size', fs)
.attr('fill', d => d3.lab(fills.get(d)).l < 60 ? '#fff' : '#111')
.style('pointer-events', 'none')
.text(d => cf.format(d.sum));
}
g.selectAll('text.x-lab').data(xs).join('text')
.attr('class', 'd3-axis-filter')
.attr('data-row-idx', d => (xIdx.get(d) || []).join(','))
.attr('transform', d => `translate(${x(d) + x.bandwidth() / 2},${ph + 8}) rotate(-35)`)
.attr('text-anchor', 'end').attr('font-size', fs).attr('fill', fg)
.style('cursor', 'pointer')
.text(d => d);
g.selectAll('text.y-lab').data(ys).join('text')
.attr('class', 'd3-axis-filter')
.attr('data-row-idx', d => (yIdx.get(d) || []).join(','))
.attr('x', -8).attr('y', d => y(d) + y.bandwidth() / 2)
.attr('text-anchor', 'end').attr('dominant-baseline', 'central')
.attr('font-size', fs).attr('fill', fg)
.style('cursor', 'pointer')
.text(d => d);
const xt = svg.append('text').attr('x', margin.left + pw / 2).attr('y', H - 8)
.attr('text-anchor', 'middle').attr('font-size', fs).attr('fill', fg);
xt.text('Neighborhood (by total Sum of Cost)');
svg.append('text').attr('transform', `translate(12,${margin.top + ph / 2}) rotate(-90)`)
.attr('text-anchor', 'middle').attr('font-size', fs).attr('fill', fg)
.text('Complaint Type (by total Sum of Cost)');
const lx = W - 80;
svg.append('text').attr('x', lx).attr('y', margin.top + fs).attr('font-size', fs).attr('fill', fg)
.text('Sum of Cost');
ramp.drawLegend(svg, {
x: lx, y: margin.top + fs + 10, width: 14, height: Math.min(180, ph - 30),
fontSize: fs, fg, format: v => cf.format(v)
});
}
Keep going
This chart was made by RegiaBI from the data above. Get it for Power BI or see pricing.
New articles in your inbox
Drop your email and we'll tell you when we publish something new. No spam — unsubscribe anytime.