About
This prototype data explorer tool provides provisional weekly death statistics for England and Wales from the Office for National Statistics (2025 onwards). This tool uses data from the Weekly Deaths Datasets.
A death occurrence is the date someone has died. A death registration is when that death is registered. The time it takes for a death to be registered can vary for multiple reasons. Currently, mortality statistics are registration-based.
If you like this prototype data explorer and would like it to be maintained or developed please let us know!
For more information please see the Weekly Deaths Dashboard and user guide on the ONS website.
Time Series
Plotly = require("https://cdn.plot.ly/plotly-2.27.0.min.js")
// `transpose()` essentially turns a "column-oriented" table into a row-wise array of objects.
death_data_raw = transpose(death_data)
function layoutScale(w) {
const isNarrow = w < 600;
return {
isNarrow: isNarrow,
titleFont: { size: isNarrow ? 14 : 16 },
axisTitle: { size: isNarrow ? 12 : 14 },
// time Series Margins
marginsTS: {
l: isNarrow ? 40 : 80,
r: 15,
t: isNarrow ? 30 : 60,
b: isNarrow ? 85 : 44
},
// bar chart margins
marginsBar: {
l: 60,
r: 20,
t: isNarrow ? 25 : 40,
b: isNarrow ? 80 : 40
},
standoffX: isNarrow ? 12 : 16,
standoffY: isNarrow ? 5 : 16,
tickAngleX: isNarrow ? -45 : 0
};
}
death_data_parsed = death_data_raw.map(d => ({
series: d.series,
week_ending: new Date(d.week_ending_str),
week_number: +d.week_number,
year: +d.year,
area_of_usual_residence: d.area_of_usual_residence,
sex: d.sex,
age_band: d.age_band,
age_order: +d.age_order,
number_of_deaths: +d.number_of_deaths
}));
death_data_parsed_regions = death_data_parsed.filter(d =>
d.area_of_usual_residence !== "England, Wales and non-residents"
);
death_data_parsed_ewnr = death_data_parsed.filter(d =>
d.area_of_usual_residence === "England, Wales and non-residents"
);
// unique values
unique_series = ["Registrations", "Occurrences"]
unique_weeks = Array.from(new Set(death_data_parsed_regions.map(d => d.week_number))).sort((a,b)=>a-b)
unique_regions = Array.from(new Set(death_data_parsed_regions.map(d => d.area_of_usual_residence))).sort()
unique_sex = ["Male", "Female"]
unique_ages = ["0-14 years","15-44 years","45-64 years","65-74 years","75-84 years","85+ years"]
// colours - hex codes copied from ons website
color_primary = "#003C57"
color_secondary = "#a8bd3a"
color_accent = "#00a3a6"
color_warning = "#206095"
// logic to switch colour based on sex selection
current_sex_color = {
// if both are selected (length 2) or nothing selected (length 0), use default
if (selected_sex.length === 2 || selected_sex.length === 0) {
return color_primary;
}
// if only Male is selected
else if (selected_sex.includes("Male")) {
return "#206095";
}
// if only Female is selected
else {
return "#00a3a6";
}
}
// create the default state: automatically show latest week selected for bar charts.
// we compute the most recent week number and use it as the default selection.
// NOTE: This affects the bar charts.
latestWeek = d3.max(unique_weeks)
filtered_data_regions = death_data_parsed_regions.filter(d =>
d.series === selected_series &&
d.year === selected_year &&
d.week_number === selected_week &&
selected_sex.includes(d.sex)
);
filtered_data_ewnr = death_data_parsed_ewnr.filter(d =>
d.series === selected_series &&
d.year === selected_year &&
d.week_number === selected_week &&
selected_sex.includes(d.sex)
);
// format a date as "17 Oct 2025" and ensure UK style
formatWeekEnding = date =>
date?.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }) ?? "–"
// for the chart titles find the latest week-ending date present in the current selection.
// if multiple weeks are selected, this picks the most recent to show in the title
selected_week_end_date =
(filtered_data_regions.length
? d3.max(filtered_data_regions, d => d.week_ending)
: null)
selected_week_title = `Week ending ${formatWeekEnding(selected_week_end_date)}`
// dynamic titles for selected sex
// determine sex label for title
sexTitle = (() => {
if (selected_sex.length === 2 || selected_sex.length === 0) {
return "";
} else if (selected_sex.includes("Male")) {
return "(Male)";
} else {
return "(Female)";
}
})();
// label: timeseries-chart
{
// build a df that that IGNORES selected_weeks so TS always shows all weeks
// rolling 12 months window based on the latest available week in the dataset
const latestDate = d3.max(death_data_parsed_ewnr, d => d.week_ending);
const cutoffDate = d3.timeMonth.offset(latestDate, -12);
const ts_rows = death_data_parsed_ewnr.filter(d =>
d.series === selected_series &&
selected_sex.includes(d.sex) &&
d.week_ending >= cutoffDate
);
// aggregate by week (sum over all selected sexes)
let ts_map = d3.rollup(
ts_rows,
v => d3.sum(v, d => d.number_of_deaths),
d => d.week_ending.toISOString()
);
let ts_array = Array.from(ts_map, ([date, deaths]) => ({ date: new Date(date), deaths }))
.sort((a,b) => a.date - b.date);
//if (selected_series === "Occurrences" && ts_array.length > 0) ts_array = ts_array.slice(0, -1);
const trace = {
x: ts_array.map(d => d.date),
y: ts_array.map(d => d.deaths),
type: 'scatter',
mode: 'lines+markers',
name: selected_series,
marker: { size: 8, color: selected_series === "Registrations" ? current_sex_color : color_secondary },
line: { width: 4, color: selected_series === "Registrations" ? current_sex_color : color_secondary },
hovertemplate: 'Week ending: %{x|%d %b %Y}<br>Deaths: %{y:,.0f}<extra></extra>'
};
const div = (this && this.style) ? this : DOM.element('div');
// hard-stop any transient overflow inside the card
div.style.width = '100%';
div.style.height = '100%';
// measure the container and pin the layout size to integer pixels
const rect = div.getBoundingClientRect();
const w = Math.floor(rect.width);
const h = Math.floor(rect.height);
const scale = layoutScale(w);
const layout = {
title: {
text: `<b>Weekly Deaths - ${selected_series} ${sexTitle}</b>`,
// Use dynamic font size
font: { ...scale.titleFont, color: '#333', family: 'Open Sans, sans-serif' },
x: 0, xanchor: 'left'
},
xaxis: {
title: {
text: 'Week ending',
font: { ...scale.axisTitle, family: 'Open Sans, sans-serif' },
standoff: scale.standoffX
},
tickfont: { family: 'Open Sans, sans-serif', size: 12 },
showgrid: true,
gridcolor: '#f0f0f0',
automargin: false, // turn off automargin so our manual margins take precedence
tickangle: scale.tickAngleX
},
yaxis: {
title: {
text: 'Number of deaths',
font: { ...scale.axisTitle, family: 'Open Sans, sans-serif' },
standoff: scale.standoffY
},
tickfont: { family: 'Open Sans, sans-serif', size: 12 },
showgrid: true,
gridcolor: '#f0f0f0',
tickformat: ',d',
automargin: true
},
plot_bgcolor: '#ffffff',
paper_bgcolor: '#ffffff',
margin: scale.marginsTS,
autosize: false,
width: w,
height: h
};
const config = { displayModeBar: false, responsive: true };
Plotly.react(div, [trace], layout, config);
// keep responsiveness: if the card resizes, update the plot size to the new integer pixels
if (!div._ro) {
div._ro = new ResizeObserver(entries => {
const cr = entries[0].contentRect;
Plotly.relayout(div, { width: Math.floor(cr.width), height: Math.floor(cr.height) });
});
div._ro.observe(div);
}
return div;
}viewof selected_series = Inputs.radio(unique_series, {
label: html`Data Type`,
value: "Registrations"
});
viewof selected_sex = Inputs.checkbox(unique_sex, {
label: html`Sex`,
value: unique_sex
});
// year
defaultYear = d3.max(unique_years);
unique_years = Array.from(new Set(death_data_parsed_regions.map(d => d.year)))
.sort((a, b) => a - b);
viewof selected_year = Inputs.select(unique_years, {
label: html`Year`,
value: defaultYear,
format: (y) => String(y)
});
// week depends on selected_year
weeks_for_year = Array.from(new Set(
death_data_parsed_regions
.filter(d => d.year === selected_year)
.map(d => d.week_number)
)).sort((a, b) => a - b);
defaultWeekForYear = d3.max(weeks_for_year);
viewof selected_week = Inputs.select(weeks_for_year, {
label: html`Week number`,
value: defaultWeekForYear
});Deaths by Region
regional_totals = d3.rollup(filtered_data_regions, v => d3.sum(v, d => d.number_of_deaths), d => d.area_of_usual_residence)
regional_array = Array.from(regional_totals, ([region, deaths]) => ({ region, deaths }))
.sort((a, b) => b.deaths - a.deaths)
{
const trace = {
y: regional_array.map(d => d.region),
x: regional_array.map(d => d.deaths),
type: 'bar', orientation: 'h',
marker: { color: current_sex_color, line: { color: '#333', width: 1 } },
hovertemplate: '%{y}<br>Deaths: %{x:,.0f}<extra></extra>'
};
const div = (this && this.style) ? this : DOM.element('div');
div.style.width = '100%';
div.style.height = '100%';
div.style.overflow = 'hidden';
const rect = div.getBoundingClientRect();
const w = Math.floor(rect.width);
const h = Math.floor(rect.height);
// estimate left margin from longest label (characters × 8px + base)
const longest = regional_array.reduce((m, d) => Math.max(m, d.region.length), 0);
const leftMargin = Math.min(180, Math.max(60, 8 * longest + 28));
const scale = layoutScale(w);
const layout = {
title: {
text: `<b>${selected_series} for ${selected_week_title} (Week ${selected_week}, ${selected_year})</b>`,
font: { ...scale.titleFont, family: 'Open Sans, sans-serif', color: '#333333' },
x: 0, xanchor: 'left'
},
xaxis: {
title: {
text: 'Number of deaths',
font: { ...scale.axisTitle, family: 'Open Sans, sans-serif' }
},
tickfont: { family: 'Open Sans, sans-serif', size: 11},
showgrid: true,
gridcolor: '#f0f0f0'
},
yaxis: {
title: '',
tickfont: { family: 'Open Sans, sans-serif', size: 12 },
automargin: true
},
margin: {
t: scale.marginsBar.t,
b: scale.isNarrow ? 45 : scale.marginsBar.b,
l: leftMargin,
r: scale.marginsBar.r
},
plot_bgcolor: '#ffffff',
paper_bgcolor: '#ffffff',
autosize: false,
width: w,
height: h
};
const config = { displayModeBar: false, responsive: true };
Plotly.react(div, [trace], layout, config);
if (!div._ro) {
div._ro = new ResizeObserver(entries => {
const cr = entries[0].contentRect;
Plotly.relayout(div, { width: Math.floor(cr.width), height: Math.floor(cr.height) });
});
div._ro.observe(div);
}
return div;
}Deaths by Age and Sex
age_order_key = age => {
const m = /(\d+)/.exec(age || "");
return m ? +m[1] : Number.POSITIVE_INFINITY;
}
// determine the order of age bands on the Y axis.
// if a global list `unique_ages` exists (defined elsewhere), use that order;
// otherwise, derive the distinct set of age bands from the current data and
// sort them using the numeric key above (youngest first).
ordered_ages = (typeof unique_ages !== "undefined" && Array.isArray(unique_ages) && unique_ages.length)
? unique_ages.slice()
: Array.from(new Set((filtered_data_ewnr || []).map(d => d.age_band))).sort((a,b) => age_order_key(a) - age_order_key(b))
// we aggregate deaths by age band and sex for the current selection.
// `filtered_data_ewnr` already applies the filters (series, sex, and the selected week).
age_sex_pyramid_data = {
// defensive default: if filtered_data_ewnr is missing then fall back to an empty array.
const age_rows = filtered_data_ewnr || [];
// d3.rollup essentially groups rows first by age band, then by sex, and sums deaths
// the result is a nested map: Map(age_band -> Map(sex -> total_deaths))
const rolled_ages = d3.rollup(age_rows, v => d3.sum(v, d => +(d.number_of_deaths || 0)), d => d.age_band, d => d.sex);
// now we populate two arrays for plotly:
// - `male` with negative values (so bars appear on the left),
// - `female` with positive values (bars to the right)
// here also "track" totals to compute percentages in tooltips
const displayLabel = age => age.replace('-', ' to ');
const order = ordered_ages;
const male = []; const female = [];
let total = 0; const totalBySex = new Map([["Male",0],["Female",0]]);
// now loop through age bands in display order and pull out male/female totals
for (const age of order) {
// get the inner map for this age band, or an empty one if absent
const bySex = rolled_ages.get(age) || new Map();
const m = +(bySex.get("Male") || 0);
const f = +(bySex.get("Female") || 0);
// update totals used for percentage calculations
total += (m+f);
totalBySex.set("Male", totalBySex.get("Male") + m);
totalBySex.set("Female", totalBySex.get("Female") + f);
male.push({ age, value: -m, abs: m });
female.push({ age, value: f, abs: f });
}
return { order, male, female, total, totalBySex };
}
{
const { order, male, female, total, totalBySex } = age_sex_pyramid_data;
const div = (this && this.style) ? this : DOM.element('div');
div.style.width = '100%';
div.style.height = '100%';
// early exit remains unchanged
const maxAbs = Math.max(
d3.max(male, d => d?.abs || 0) || 0,
d3.max(female, d => d?.abs || 0) || 0
);
if (!order.length || maxAbs === 0) {
div.innerHTML = "<div style='display:flex;align-items:center;justify-content:center;height:100%;color:#666;'><em>selection empty.</em></div>";
return div;
}
if (div.innerHTML.includes("selection empty")) div.innerHTML = "";
const niceMax = d3.ticks(0, maxAbs * 1.1, 5).slice(-1)[0] || maxAbs;
const posTicks = d3.ticks(0, niceMax, 5).slice(1);
const tickvals = [...posTicks.map(t => -t), 0, ...posTicks];
const ticktext = tickvals.map(v => d3.format(",d")(Math.abs(v)));
const mTotal = totalBySex.get("Male") || 0;
const fTotal = totalBySex.get("Female") || 0;
const mkCD = d => [d.abs, total ? (d.abs/total*100) : 0, mTotal ? (d.abs/mTotal*100) : 0];
const fkCD = d => [d.abs, total ? (d.abs/total*100) : 0, fTotal ? (d.abs/fTotal*100) : 0];
const displayLabel = age => age.replace('-', ' to ');
const maleTrace = {
y: order.map(displayLabel), x: male.map(d => d.value), customdata: male.map(mkCD),
name: "Male", type: "bar", orientation: "h", marker: { color: "#206095" },
hovertemplate: "%{y}<br>Male deaths: %{customdata[0]:,.0f}<br>Share of total: %{customdata[1]:.1f}%<br>Within male: %{customdata[2]:.1f}%<extra></extra>"
};
const femaleTrace = {
y: order.map(displayLabel), x: female.map(d => d.value), customdata: female.map(fkCD),
name: "Female", type: "bar", orientation: "h", marker: { color: "#00a3a6" },
hovertemplate: "%{y}<br>Female deaths: %{customdata[0]:,.0f}<br>Share of total: %{customdata[1]:.1f}%<br>Within female: %{customdata[2]:.1f}%<extra></extra>"
};
const rect = div.getBoundingClientRect();
const w = Math.floor(rect.width);
const h = Math.floor(rect.height);
const scale = layoutScale(w);
const layout = {
title: {
text: `<b>${selected_series} for ${selected_week_title} (Week ${selected_week}, ${selected_year})</b>`,
font: { color: '#333333', size: scale.titleFont.size }, // use scaled font size
x: 0,
xanchor: 'left'
},
barmode: "overlay",
xaxis: {
title: {
text: 'Number of deaths',
font: { ...scale.axisTitle, family: 'Open Sans, sans-serif' }
},
tickfont: { family: 'Open Sans, sans-serif', size: 12 },
range: [-niceMax, niceMax],
tickvals,
ticktext,
zeroline: true,
zerolinecolor: "#555",
zerolinewidth: 1.5,
gridcolor: "rgba(0,0,0,0.06)",
automargin: true
},
yaxis: {
title: "",
tickfont: { family: 'Open Sans, sans-serif', size: 13 },
categoryorder: "array",
categoryarray: order.map(displayLabel),
automargin: true
},
legend: {
orientation: "h",
x: 0.5,
xanchor: 'center', // center the legend horizontally
y: -0.18, // push lower on small screens
yanchor: 'top'
},
// use the dynamic margins defined earlier
margin: {
t: scale.marginsBar.t,
b: 20,
l: 40,
r: 40
},
plot_bgcolor: "rgba(0,0,0,0)",
paper_bgcolor: "rgba(0,0,0,0)",
autosize: false,
width: w,
height: h
};
const config = { displayModeBar: false, responsive: true };
Plotly.react(div, [maleTrace, femaleTrace], layout, config);
if (!div._ro) {
div._ro = new ResizeObserver(entries => {
const cr = entries[0].contentRect;
Plotly.relayout(div, { width: Math.floor(cr.width), height: Math.floor(cr.height) });
});
div._ro.observe(div);
}
return div;
}About Registration Delays
The registration delay for a death is the time between a death occurring and being registered (registration delay).
Bank holidays, workloads of doctors certifying deaths and other closures of registration offices can all affect the timeliness of a death being registered.
Death certification reform implemented in England and Wales on 9 September 2024 affected registration delays.
For further information please see the Impact of registration delays on mortality statistics dataset
All data used in charts on this page is available from the Weekly Deaths Datasets.
Death registrations (England, Wales and non-residents)
delay_data_raw = transpose(delay_data);
bh_data_raw = transpose(bh_data);
// Parse and type-clean delay data
delay_data_parsed = delay_data_raw.map(d => ({
series: d.series,
week_ending: new Date(d.week_ending_str),
week_number: +d.week_number,
year: +d.year,
area_of_usual_residence: d.area_of_usual_residence,
certification_type: d.certification_type,
place_of_occurrence: d.place_of_occurrence,
median_delay: +d.median_delay,
lq_delay: +d.lq_delay,
uq_delay: +d.uq_delay,
perc_within_7_days: +d.perc_within_7_days,
number_of_deaths: +d.number_of_deaths
}));
// Function to wrap long EW&nr text for legend
pretty_ew_text = s =>
s === "England, Wales and non-residents"
? "England, Wales <br>and non-residents"
: s;
// Function to map areas to colours
delay_area_colour_map = area =>
({
"England, Wales and non-residents": "#206095",
"England": "#27a0cc",
"Wales": "#f66068",
"North East": "#a8bd3a",
"North West": "#871a5b",
"Yorkshire and The Humber": "#22d0b6",
"East Midlands": "#746cb1",
"West Midlands": "#05341a",
"East of England": "#003c57",
"London": "#f8ab00",
"South East": "#6f7c85",
"South West": "#7b4f2c"
}[area] ?? "#6f7c85");
// Filter data based on selected options
filtered_delay_data = delay_data_parsed.filter(d =>
d.year === selected_delay_year &&
d.week_number === selected_delay_week &&
(selected_delay_area.length === 0 ||
selected_delay_area.some(opt => opt === d.area_of_usual_residence))
);
// Determine selected end date
selected_delay_end_date =
filtered_delay_data.length
? d3.max(filtered_delay_data, d => d.week_ending)
: null;
// Title string
delay_week_info_for_titles =
`Week ending ${formatWeekEnding(selected_delay_end_date)} ` +
`(Week ${selected_delay_week}, ${selected_delay_year})`;
// Block for delay ts chart
{
const latestDelayDate = d3.max(delay_data_parsed, d => d.week_ending);
const cutoffDelayDate = d3.timeDay.offset(
d3.min(delay_data_parsed, d => d.week_ending),
-7
);
const dcrDate = new Date("2024-09-11");
const ts_delay_rows = delay_data_parsed.filter(
d =>
d.certification_type === "All certification types" &&
d.place_of_occurrence === "All places" &&
d.area_of_usual_residence === "England, Wales and non-residents"
);
const ts_delay_rows_sorted = ts_delay_rows
.map(d => ({
week_ending: d.week_ending,
median_delay: +d.median_delay,
perc_within_7_days: +d.perc_within_7_days,
lq_delay: +d.lq_delay,
uq_delay: +d.uq_delay
}))
.sort((a, b) => a.week_ending - b.week_ending);
const bh_data_filtered = bh_data_raw
.map(d => ({
bh_date: new Date(d.bh_date_str)
}))
.filter(d => d.bh_date <= latestDelayDate && d.bh_date >= cutoffDelayDate)
.sort((a, b) => a.bh_date - b.bh_date);
//----------------------------------------------
// 1. ROW 1 — Percentage registered within 7 days
//----------------------------------------------
const pct_trace = {
x: ts_delay_rows_sorted.map(d => d.week_ending),
y: ts_delay_rows_sorted.map(d => d.perc_within_7_days),
type: "scatter",
mode: "lines+markers",
name: "Percentage of deaths registered within 7 days",
marker: { size: 6, color: "#1f77b4" },
line: { width: 3, color: "#1f77b4" },
hovertemplate:
"<b>Week ending: %{x|%d %b %Y}</b><br>" +
"Percentage registered within 7 days: %{y:.1f}%<extra></extra>",
xaxis: "x",
yaxis: "y"
};
//----------------------------------------------
// 2. ROW 2 — Delay chart
//----------------------------------------------
// Lower quartile — first ribbon boundary (hidden line)
const lq_delay_trace = {
x: ts_delay_rows_sorted.map(d => d.week_ending),
y: ts_delay_rows_sorted.map(d => d.lq_delay),
type: "scatter",
mode: "lines",
name: "Lower quartile (Q1)",
line: { width: 0 }, // hide the edge line (optional)
hoverinfo: "skip", // band hover handled on Q3 trace
showlegend: false,
legendgroup: "iqr",
xaxis: "x2",
yaxis: "y2"
};
// Upper quartile — second boundary + fill
const uq_delay_trace = {
x: ts_delay_rows_sorted.map(d => d.week_ending),
y: ts_delay_rows_sorted.map(d => d.uq_delay),
type: "scatter",
mode: "lines",
name: "Upper and lower quartile delay",
line: { width: 0 }, // hide the edge line (optional)
fill: "tonexty", // <-- key: fills to the previous trace (Q1)
fillcolor: "rgba(31, 119, 180, 0.20)", // match your palette
hovertemplate:
"Lower quartile: %{customdata:.0f}<br>" +
"Upper quartile: %{y:.0f}<extra></extra>",
// Pass Q1 into customdata if you want it in hovertemplate
customdata: ts_delay_rows_sorted.map(d => d.lq_delay),
legendrank: 2,
legendgroup: "iqr",
xaxis: "x2",
yaxis: "y2"
};
// Median line (the only trace with tooltip)
const median_delay_trace = {
x: ts_delay_rows_sorted.map(d => d.week_ending),
y: ts_delay_rows_sorted.map(d => d.median_delay),
type: "scatter",
mode: "lines+markers",
name: "Median registration delay",
marker: { size: 8, color: color_primary },
line: { width: 4, color: color_primary },
hovertemplate:
"<b>Week ending: %{x|%d %b %Y}</b><br>" +
"Median registration delay: %{y:,.0f}<extra></extra>",
legendrank: 1,
xaxis: "x2",
yaxis: "y2"
};
//----------------------------------------------
// 3. Bank holidays - along x axis
//----------------------------------------------
const bh_trace = {
x: bh_data_filtered.map(d => d.bh_date),
y: bh_data_filtered.map(d => 0.7), // pinned to bottom
type: "scatter",
mode: "markers",
marker: { size: 8, color: "grey" },
name: "Bank holiday",
hoverinfo: "skip",
xaxis: "x2",
yaxis: "y2"
};
const bh_trace_2 = {
x: bh_data_filtered.map(d => d.bh_date),
y: bh_data_filtered.map(d => 2), // pinned to bottom
type: "scatter",
mode: "markers",
marker: { size: 8, color: "grey" },
hoverinfo: "skip",
showlegend: false,
xaxis: "x",
yaxis: "y"
};
const div = (this && this.style) ? this : DOM.element("div");
// Hard-stop any transient overflow inside the card
div.style.width = "100%";
div.style.height = "100%";
// Measure the container and pin the layout size to integer pixels
const rect = div.getBoundingClientRect();
const w = Math.floor(rect.width);
const h = Math.floor(rect.height);
const scale = layoutScale(w);
const maxY = Math.max(...uq_delay_trace.y);
const delay_layout = {
grid: { rows: 2, columns: 1, pattern: "independent", roworder: "top to bottom" },
hovermode: "x unified",
// Styling for unified hover box
hoverlabel: {
bgcolor: "#fff",
font: { color: "#333" },
align: "left",
namelength: -1
},
// ROW 1 axes
xaxis: {
hoverformat: "",
title: { text: "" },
showticklabels: false, // hide tick labels
ticks: "", // hide tick marks
showgrid: true, // keep grid on
tickfont: { family: "Open Sans, sans-serif", size: 12 },
gridcolor: "#f0f0f0",
automargin: false, // manual margins take precedence
tickangle: scale.tickAngleX
},
yaxis: {
title: {
text: "Percentage",
standoff: scale.standoffY
},
automargin: true,
rangemode: "tozero",
ticksuffix: "%"
},
// ROW 2 axes
xaxis2: {
anchor: "y2",
title: {
text: "Week ending",
standoff: 5
}
},
yaxis2: {
title: {
text: "Days",
standoff: scale.standoffY
},
tickfont: { family: "Open Sans, sans-serif", size: 12 },
showgrid: true,
gridcolor: "#f0f0f0",
tickformat: ",d",
automargin: true,
autorange: false,
range: [0, maxY * 1.1]
},
annotations: [
{
text: "<b>Percentage of deaths registered within 7 days</b>",
x: 0,
y: 1.07,
xref: "paper",
yref: "paper",
showarrow: false,
xanchor: "left",
font: { ...scale.axisTitle, size: scale.axisTitle.size + 2 }
},
{
text: "<b>Registration delay</b>",
x: 0,
y: 0.48,
xref: "paper",
yref: "paper",
showarrow: false,
xanchor: "left",
font: { ...scale.axisTitle, size: scale.axisTitle.size + 2 }
}
],
legend: {
orientation: "h",
y: -0.13, // move the legend below the chart
x: 0.5,
xanchor: "center",
yanchor: "top"
},
plot_bgcolor: "#ffffff",
paper_bgcolor: "#ffffff",
margin: scale.marginsTS,
autosize: false,
width: w,
height: h
};
delay_layout.shapes = [
// --- Bottom chart (delay plot) ---
{
type: "line",
x0: dcrDate,
x1: dcrDate,
y0: 0,
y1: maxY * 1.1,
xref: "x2",
yref: "y2",
line: {
color: "grey",
width: 2,
dash: "dash"
}
},
// --- Top chart (percentage plot) ---
{
type: "line",
x0: dcrDate,
x1: dcrDate,
y0: 0,
y1: 50, // Appropriate for 2024-2026
xref: "x",
yref: "y",
line: {
color: "grey",
width: 2,
dash: "dash"
}
}
];
delay_layout.annotations = [
...delay_layout.annotations,
// DCR label
{
x: dcrDate,
y: maxY * 1.1,
xref: "x2",
yref: "y2",
text: "Death certification reform",
showarrow: false,
font: { color: "dark grey", size: 14 },
xanchor: "middle",
yanchor: "bottom"
}
];
const config = { displayModeBar: false, responsive: true };
Plotly.react(
div,
[pct_trace, bh_trace, bh_trace_2, lq_delay_trace, uq_delay_trace, median_delay_trace],
delay_layout,
config
);
// Keep responsiveness: if the card resizes, update the plot size to the new integer pixels
if (!div._ro) {
div._ro = new ResizeObserver(entries => {
const cr = entries[0].contentRect;
Plotly.relayout(div, {
width: Math.floor(cr.width),
height: Math.floor(cr.height)
});
});
div._ro.observe(div);
}
div.className = "delay-ts-chart";
return div;
}defaultDelayYear = d3.max(unique_delay_years);
unique_delay_years = Array.from(new Set(delay_data_parsed.map(d => d.year)))
.filter(d => !isNaN(d))
.sort((a, b) => a - b);
viewof selected_delay_year = Inputs.select(unique_delay_years, {
label: html`Year`,
value: defaultDelayYear,
format: (y) => String(y)
});
// week depends on selected_year
weeks_for_year_delay = Array.from(new Set(
delay_data_parsed
.filter(d => !isNaN(d.year) && d.year === selected_delay_year)
.map(d => d.week_number)
)).sort((a, b) => a - b);
defaultDelayWeekForYear = d3.max(weeks_for_year_delay);
viewof selected_delay_week = Inputs.select(weeks_for_year_delay, {
label: html`Week number`,
value: defaultDelayWeekForYear
});
// Unique areas
unique_areas_delay = Array.from(
new Set(delay_data_parsed.map(d => d.area_of_usual_residence))
).sort(d3.ascending);
// Default value
default_delay_area = ["England, Wales and non-residents"];
// Build the selector
viewof selected_delay_area = Inputs.select(unique_areas_delay, {
label: html`Area of usual residence<br><span style="font-weight: normal; color:#555;">(Use Ctrl to select multiple values)</span>`,
value: default_delay_area,
multiple: true
});Registered deaths by certification type
excluded_cert_types = [
"Unknown/Uncertified",
"Certified by coroner with inquest",
"Certified by coroner with no inquest",
"Certified by medical examiner"
];
// 1) Filter: all places only + exclusions
group_base = filtered_delay_data.filter(d =>
d.place_of_occurrence === "All places" &&
!excluded_cert_types.includes(d.certification_type)
);
// 2) Get all areas present in this filtered slice
areas = Array.from(
new Set(group_base.map(d => d.area_of_usual_residence))
).sort(d3.ascending);
// 3) Certification types (keep consistent x-order)
cert_types = Array.from(
new Set(group_base.map(d => d.certification_type))
).sort(d3.ascending);
// Block for cert type chart
{
// 4) Build one Plotly trace per area (grouped bars)
const delay_cert_traces = areas.map(area => {
const yvals = cert_types.map(cert => {
const row = group_base.find(
d =>
d.certification_type === cert &&
d.area_of_usual_residence === area
);
return row ? row.perc_within_7_days : null;
});
const deaths = cert_types.map(cert => {
const row = group_base.find(
d =>
d.certification_type === cert &&
d.area_of_usual_residence === area
);
return row ? row.number_of_deaths : null;
});
return {
x: cert_types,
y: yvals,
name: pretty_ew_text(area),
type: "bar",
marker: { color: delay_area_colour_map(area) },
customdata: deaths.map(v => [v]),
hovertemplate:
"<b>%{x}</b><br>" +
"Area: " + area + "<br>" +
"Percentage registered within 7 days: %{y:.1f}%<br>" +
"Number of deaths: %{customdata[0]:,}<extra></extra>"
};
});
// 5) Layout
const delay_cert_layout = {
title: {
text: `<b>Percentage registered within 7 days</b><br>${delay_week_info_for_titles}`,
x: 0,
xanchor: "left",
font: { family: "Open Sans, sans-serif" }
},
barmode: "group",
xaxis: {
title: "Certification type",
tickangle: -20
},
yaxis: {
title: "Percentage",
ticksuffix: "%",
rangemode: "tozero"
},
legend: {
title: { text: "Area" }
},
showlegend: true,
margin: { t: 60, b: 80, l: 70, r: 30 },
plot_bgcolor: "#fff",
paper_bgcolor: "#fff"
};
// 6) Render
const cert_div = DOM.element("cert_type_div");
cert_div.style.width = "100%";
cert_div.style.overflow = "visible";
Plotly.newPlot(
cert_div,
delay_cert_traces,
delay_cert_layout,
{ displayModeBar: false, responsive: true }
);
Plotly.Plots.resize(cert_div);
return cert_div;
}Registered deaths by place of death
excluded_place_of_occ = ["All places"];
// 1) Filter: certification_type fixed, exclude "All places"
place_base = filtered_delay_data.filter(d =>
d.certification_type === "All certification types" &&
!excluded_place_of_occ.includes(d.place_of_occurrence)
);
// 2) Areas present
areas_for_place = Array.from(
new Set(place_base.map(d => d.area_of_usual_residence))
).sort(d3.ascending);
// 3) Places of occurrence (x‑axis order)
place_of_occ = Array.from(
new Set(place_base.map(d => d.place_of_occurrence))
).sort(d3.ascending);
// Block for place of occurrence chart
{
// 4) Build one Plotly trace per area
const delay_place_traces = areas_for_place.map(area => {
const yvals = place_of_occ.map(place => {
const row = place_base.find(
d =>
d.place_of_occurrence === place &&
d.area_of_usual_residence === area
);
return row ? row.perc_within_7_days : null; // gap if missing
});
const deaths = place_of_occ.map(place => {
const row = place_base.find(
d =>
d.place_of_occurrence === place &&
d.area_of_usual_residence === area
);
return row ? row.number_of_deaths : null;
});
return {
x: place_of_occ,
y: yvals,
name: pretty_ew_text(area),
type: "bar",
// customdata expects an array per point; wrap death counts as [value]
marker: { color: delay_area_colour_map(area) },
customdata: deaths.map(v => [v]),
hovertemplate:
"<b>%{x}</b><br>" +
"Area: " + area + "<br>" +
"Percentage registered within 7 days: %{y:.1f}%<br>" +
"Number of deaths: %{customdata[0]:,}<extra></extra>"
};
});
// 5) Layout
const delay_place_layout = {
title: {
text: `<b>Percentage registered within 7 days</b><br>${delay_week_info_for_titles}`,
x: 0,
xanchor: "left",
font: { family: "Open Sans, sans-serif" }
},
barmode: "group",
xaxis: {
title: "Place of occurrence",
tickangle: -20
},
yaxis: {
title: "Percentage",
ticksuffix: "%",
rangemode: "tozero"
},
legend: {
title: { text: "Area" }
},
showlegend: true,
margin: { t: 60, b: 80, l: 70, r: 30 },
plot_bgcolor: "#fff",
paper_bgcolor: "#fff"
};
// 6) Render
const place_div = DOM.element("delay_place_div");
place_div.style.width = "100%";
place_div.style.overflow = "visible";
Plotly.newPlot(
place_div,
delay_place_traces,
delay_place_layout,
{ displayModeBar: false, responsive: true }
);
Plotly.Plots.resize(place_div);
return place_div;
}