viewof query = Inputs.text({label: "Search notices", placeholder: "Brand, product, or part"})
viewof countries = Inputs.checkbox(["United States", "Canada"], {label: "Country", value: ["United States", "Canada"]})
viewof yearFrom = Inputs.range([minYear, maxYear], {step: 1, value: minYear, label: "From"})
viewof yearTo = Inputs.range([minYear, maxYear], {step: 1, value: maxYear, label: "To"})
viewof form = Inputs.select(["All", ...forms], {label: "What was recalled"})
viewof component = Inputs.select(["All", ...components], {label: "Failed part"})
viewof hazard = Inputs.select(["All", ...hazards], {label: "Hazard"})
viewof ebikeOnly = Inputs.toggle({label: "E-bike related only", value: false})
viewof includeProbable = Inputs.toggle({label: "Include probable cases", value: true})
viewof measure = Inputs.radio(["Recall events", "Units recalled"], {label: "Count", value: "Recall events"})
viewof view = Inputs.radio(["By hazard", "By failed part"], {label: "Chart", value: "By hazard"})
viewof reset = Inputs.button("Reset all filters", {reduce: () => {
setInput(viewof query, "");
setInput(viewof countries, ["United States", "Canada"]);
setInput(viewof yearFrom, minYear);
setInput(viewof yearTo, maxYear);
setInput(viewof form, "All");
setInput(viewof component, "All");
setInput(viewof hazard, "All");
setInput(viewof ebikeOnly, false);
setInput(viewof includeProbable, true);
}})Dashboard
Filter the recalls any way you like. Every panel updates together.
data = transpose(recs)
maxYear = [].concat(meta.maxYear)[0]
minYear = [].concat(meta.minYear)[0]
lastUpdated = [].concat(meta.lastUpdated)[0]
forms = [].concat(meta.forms)
components = [].concat(meta.components)
hazards = [].concat(meta.hazards)
hazardColors = ebCatFill.slice(0, 4) // cobalt, tomato, sunflower, kelp
fmtN = d3.format(",")
// Set a filter control from code (used by the heatmap and the reset button)
setInput = (input, value) => {
input.value = value;
input.dispatchEvent(new Event("input", {bubbles: true}));
}
// Search text for each recall event: the titles of every notice in it, so a
// joint recall matches a word in either the US or the Canadian title
eventText = d3.rollup(data, v => v.map(d => `${d.title} ${d.product_form} ${d.failed_component} ${d.hazard_group}`).join(" ").toLowerCase(), d => d.event_id)
// Countries reporting each recall event (joint events have both)
eventCountries = d3.rollup(data, v => new Set(v.map(d => d.country)), d => d.event_id)Filters
lo = Math.min(yearFrom, yearTo)
// Search words: a notice must contain every word (in any order)
terms = query.toLowerCase().split(/\s+/).filter(t => t.length)
hi = Math.max(yearFrom, yearTo)
// Does a notice pass the filters? "skip" leaves some filters out, so the
// heatmap and the country chart can show the full picture around a selection.
passes = (d, skip = []) =>
(skip.includes("country") || countries.includes(d.country)) &&
d.recall_year >= lo && d.recall_year <= hi &&
(form === "All" || d.product_form === form) &&
(skip.includes("component") || component === "All" || d.failed_component === component) &&
(skip.includes("hazard") || hazard === "All" || d.hazard_group === hazard) &&
(!ebikeOnly || d.is_ebike_related) &&
(includeProbable || d.case_status === "confirmed") &&
terms.every(t => eventText.get(d.event_id).includes(t))
// One row per recall event (the US notice, where there is one, comes first)
uniqueEvents = rows => {
const seen = new Set();
return rows.filter(d => {
if (seen.has(d.event_id)) return false;
seen.add(d.event_id);
return true;
});
}
filtered = uniqueEvents(data.filter(d => passes(d)))
heatRows = uniqueEvents(data.filter(d => passes(d, ["component", "hazard"])))
countryRows = uniqueEvents(data.filter(d => passes(d, ["country"]) && d.recall_year >= 2008))
w = d => measure === "Recall events" ? 1 : (d.units_recalled ?? 0)
measureLabel = measure === "Recall events" ? "recall events" : "units recalled"
years = d3.range(lo, hi + 1){
if (!terms.length) return html``;
const clear = html`<button type="button" class="dash-clear">Clear search</button>`;
clear.onclick = () => setInput(viewof query, "");
const note = html`<div class="dash-search-note"><span>Showing recalls matching <strong>${query.trim()}</strong>. Counts reflect how much a company sells and how readily it recalls, as well as product safety, so they are not a safety ranking.</span></div>`;
note.append(clear);
return note;
}tiles = {
const n = filtered.length;
const fall = n ? filtered.filter(d => d.hazard_group === "Fall or crash").length / n : 0;
const ranked = d3.rollups(filtered.filter(d => d.failed_component !== "Other or unclear"),
v => v.length, d => d.failed_component)
.sort((a, b) => b[1] - a[1]);
const top = ranked.length ? ranked[0] : ["None", 0];
const eb = n ? filtered.filter(d => d.is_ebike_related).length / n : 0;
const units = d3.sum(filtered, d => d.units_recalled ?? 0);
const pct = x => `${Math.round(100 * x)}%`;
return html`<div class="stat-row dash-tiles">
<div class="stat-box"><span class="num">${fmtN(n)}</span> <span class="lab">recall events (${fmtN(units)} units)</span></div>
<div class="stat-box"><span class="num">${pct(fall)}</span> <span class="lab">fall or crash hazard</span></div>
<div class="stat-box"><span class="num">${n ? pct(top[1] / n) : "0%"}</span> <span class="lab">top failed part: ${top[0].toLowerCase()}</span></div>
<div class="stat-box"><span class="num">${pct(eb)}</span> <span class="lab">e-bike related</span></div>
</div>`;
}totals = years.map(y => ({year: y, total: d3.sum(filtered.filter(d => d.recall_year === y), w)}))
// Three-year trailing average, leaving out the current (partial) year
rolling = totals
.filter(t => t.year < maxYear)
.map((t, i, arr) => i < 2 ? null : {year: t.year, avg: d3.mean(arr.slice(i - 2, i + 1), d => d.total)})
.filter(Boolean)
byHazard = years.flatMap(y => hazards.map(h => ({
year: y,
hazard: h,
value: d3.sum(filtered.filter(d => d.recall_year === y && d.hazard_group === h), w)
})))
byPart = components.flatMap(c => years.map(y => ({
component: c,
year: y,
value: d3.sum(filtered.filter(d => d.recall_year === y && d.failed_component === c), w)
}))){
if (view === "By hazard") {
const fig = ebPlot(Plot, {
width,
height: 380,
marginLeft: 56,
marginTop: 20,
x: {label: null, tickFormat: "d", domain: [lo, hi + 1]},
y: {label: measure === "Recall events" ? "Recall events per year" : "Units recalled per year", grid: true, tickFormat: "~s"},
color: {domain: hazards, range: hazardColors, legend: true},
marks: [
Plot.rectY(byHazard, {
x: "year", interval: 1, y: "value", fill: "hazard",
fillOpacity: d => d.year === maxYear ? 0.45 : 1,
insetLeft: 1, insetRight: 1, stroke: eb.ink, strokeWidth: 0.5,
tip: true,
title: d => `${d.year}${d.year === maxYear ? " (partial year)" : ""}\n${d.hazard}: ${fmtN(Math.round(d.value))} ${measureLabel}`
}),
Plot.lineY(rolling, {x: d => d.year + 0.5, y: "avg", stroke: eb.ink, strokeWidth: 2, curve: "monotone-x"}),
Plot.ruleY([0])
]
});
const wrap = html`<div class="dash-chart"></div>`;
wrap.append(fig);
return wrap;
}
const maxV = d3.max(byPart, d => d.value) || 1;
const grid = html`<div class="small-multiples"></div>`;
for (const c of components) {
const rows = byPart.filter(d => d.component === c);
const total = d3.sum(rows, d => d.value);
const p = ebPlot(Plot, {
width: 300, height: 130, marginLeft: 40, marginTop: 8,
x: {domain: [lo, hi + 1], tickFormat: "d", ticks: 4, label: null},
y: {domain: [0, maxV], ticks: 3, label: null, grid: true, tickFormat: "~s"},
marks: [
Plot.rectY(rows, {
x: "year", interval: 1, y: "value", fill: "#e3c600", stroke: eb.ink, strokeWidth: 0.4,
fillOpacity: d => d.year === maxYear ? 0.45 : 1,
insetLeft: 0.5, insetRight: 0.5,
tip: true,
title: d => `${c}, ${d.year}: ${fmtN(Math.round(d.value))} ${measureLabel}`
}),
Plot.ruleY([0])
]
});
const panel = html`<div class="sm-panel"><div class="sm-title">${c} <span class="sm-total">${fmtN(Math.round(total))}</span></div></div>`;
panel.append(p);
grid.append(panel);
}
return grid;
}html`<p class="dash-note">${view === "By hazard"
? "Bars show each year's total, split by hazard. The dark line is the three-year average. "
: ""}${maxYear} is a partial year (data to ${lastUpdated}), shown paler. Canadian notices start in 2008, so totals before then are US only. Joint US and Canadian recalls count once.${measure === "Units recalled"
? " Units are as stated in each notice: US notices usually count US units, and Canadian notices count units sold in Canada."
: ""}</p>`Which parts cause which hazards
{
const counts = new Map();
for (const d of heatRows) {
const k = d.failed_component + "|" + d.hazard_group;
counts.set(k, (counts.get(k) ?? 0) + w(d));
}
const maxV = d3.max(counts.values()) || 1;
const color = d3.scaleSequential([0, maxV], d3.interpolateRgbBasis(["#F3EEE3", "#8A9BEA", "#2340FF", "#141F80"]));
const table = html`<table class="heat">
<thead><tr><th></th>${hazards.map(h => html`<th scope="col">${h}</th>`)}</tr></thead>
<tbody></tbody>
</table>`;
const tbody = table.querySelector("tbody");
for (const c of components) {
const tr = html`<tr><th scope="row">${c}</th></tr>`;
for (const h of hazards) {
const v = counts.get(c + "|" + h) ?? 0;
const selected = component === c && hazard === h;
const td = html`<td tabindex="0">${v ? fmtN(Math.round(v)) : ""}</td>`;
td.style.background = v ? color(Math.max(v, maxV * 0.12)) : "#ffffff";
td.style.color = v > maxV * 0.5 ? "#ffffff" : "#111111";
td.title = `${c}, ${h}: ${fmtN(Math.round(v))} ${measureLabel}`;
if (selected) td.classList.add("selected");
const pick = () => {
setInput(viewof component, selected ? "All" : c);
setInput(viewof hazard, selected ? "All" : h);
};
td.onclick = pick;
td.onkeydown = e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } };
tr.append(td);
}
tbody.append(tr);
}
const wrap = html`<div class="heat-wrap"></div>`;
wrap.append(table);
return wrap;
}United States and Canada
{
const cats = ["US only", "Joint (both countries)", "Canada only"];
const catColors = ["#2340FF", "#B9A4FF", "#FF5A36"]; // US cobalt, joint lilac, Canada tomato
const yrs = d3.range(Math.max(lo, 2008), hi + 1);
if (!yrs.length) return html`<p class="dash-note">Choose years from 2008 onward to compare the two countries.</p>`;
const cat = d => {
const set = eventCountries.get(d.event_id);
if (set.size > 1) return "Joint (both countries)";
return set.has("Canada") ? "Canada only" : "US only";
};
const rows = yrs.flatMap(y => cats.map(k => ({
year: y, cat: k,
value: d3.sum(countryRows.filter(d => d.recall_year === y && cat(d) === k), w)
})));
const fig = ebPlot(Plot, {
width,
height: 300,
marginLeft: 56,
x: {label: null, tickFormat: "d", domain: [yrs[0], hi + 1]},
y: {label: measure === "Recall events" ? "Recall events per year" : "Units recalled per year", grid: true, tickFormat: "~s"},
color: {domain: cats, range: catColors, legend: true},
marks: [
Plot.rectY(rows, {
x: "year", interval: 1, y: "value", fill: "cat", order: cats,
fillOpacity: d => d.year === maxYear ? 0.45 : 1,
insetLeft: 1, insetRight: 1, stroke: eb.ink, strokeWidth: 0.5,
tip: true,
title: d => `${d.year}${d.year === maxYear ? " (partial year)" : ""}\n${d.cat}: ${fmtN(Math.round(d.value))} ${measureLabel}`
}),
Plot.ruleY([0])
]
});
const wrap = html`<div class="dash-chart"></div>`;
wrap.append(fig);
return wrap;
}Matching recalls
listRows = filtered
.map(d => ({
year: d.recall_year,
country: eventCountries.get(d.event_id).size > 1 ? "Both" : (d.country === "United States" ? "US" : "Canada"),
title: d.title,
url: d.url,
what: d.product_form,
part: d.failed_component,
hazard: d.hazard_group,
status: d.case_status
}))
.sort((a, b) => b.year - a.year)Inputs.table(listRows, {
columns: ["year", "country", "title", "what", "part", "hazard"],
header: {year: "Year", country: "Country", title: "Recall notice", what: "What was recalled", part: "Failed part", hazard: "Hazard"},
format: {
year: y => String(y),
title: (t, i, rows) => html`<a href=${rows[i].url} target="_blank" rel="noopener">${t}</a>`
},
width: {year: 60, country: 80, title: 420},
rows: 12,
layout: "auto"
})