Files
WebApp/src/app/indicadores/figures.ts
T
alberto 72d5d07d67 F2a: TEA indicators after the 3 Dec review
Changed:
- Summary: the time sentences say "La mediana de..." and the footnote is gone (nothing else used it); "se evaluaron" is now "se registraron en el tamizaje".
- boxFigure: the median, Q3 and Q1 are text annotations to the right of the box; the hover is off so nothing else is labelled.
- M23 is titled "Pacientes en tamizaje por resultado diagnostico" on the page and in Trazabilidad.
- M21/M22 ageShare: the bar text is "p % (n/N)" from numerator and denominator of strata.age_sex, and the hover reuses it.
- M28 Sankey: every node label ends with its count ("M-CHAT · 18"), the "Se quedo en..." nodes included; link labels stay without it.
- M31: the bars plot the rate per 10,000 for the selected period, one bar per sex, with the rate as bar text and confirmed of total children in the hover. The card shows a headline number that follows the sex toggle (total when both sexes). Trazabilidad plots the rate as a line per sex plus the total (new 'rate' panel kind replaces the stacked counts).
- reading() carries the per-stratum measureScore as Reading.rates; the group measureScore is the total rate.

Choices the spec left open:
- Q3, median and Q1 sit at a fixed 56 px right of the box, anchored top/middle/bottom so they do not overlap when the three values are equal.
- Headline detail line: "por 10 000 niños · n confirmados de N niños".
- The selected-sex outline on the M31 bars is black, since the bars are one trace now.
- e2e pages.spec.ts:23 already expects no toggle on the M23 card, which is what the page renders, so it stays; it now also asserts the new M23 heading.
2026-12-03 13:55:14 -06:00

731 lines
24 KiB
TypeScript

import { type Figure, PALETTE } from '../plot';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
export const SHORT = '.1~f';
const SIGNIFICANT = '.2~r';
export const percentAxis = {
type: 'linear' as const,
ticksuffix: ' %',
tickformat: '.0f',
hoverformat: SHORT,
};
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: `%{y}<br>mediana %{x:${SHORT}} días<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: {
title: { text: 'Días' },
rangemode: 'tozero',
zeroline: false,
...valueAxis(shown.flatMap((s) => [s.r!.score, s.r!.high])),
},
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1~f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
...percentAxis,
range: [0, 100.5],
dtick: 20,
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
},
};
}
function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1~f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ...percentAxis, zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
const label = (text: string, y: number, yanchor: 'top' | 'middle' | 'bottom') => ({
x: period,
y,
text: `${text} ${decimal(y)}`,
xref: 'x' as const,
yref: 'y' as const,
xanchor: 'left' as const,
yanchor,
xshift: 56,
showarrow: false,
});
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
upperfence: [q3],
marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)',
hoverinfo: 'skip',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
annotations: [
label('Q3', q3, 'bottom'),
label('Mediana', r.score!, 'middle'),
label('Q1', q1, 'top'),
],
yaxis: { title: { text: 'días' }, rangemode: 'tozero', ...valueAxis([q1, r.score!, q3]) },
},
};
}
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent:.1~%}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value:d} (%{percent:.1~%})<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `<b>${count(total)}</b><br>${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
data: [
{
type: 'bar',
orientation: 'h',
name: period,
y,
x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x:d}',
textposition: 'outside',
hovertemplate: '%{y}: %{x:d}<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: {
title: { text: axis },
rangemode: 'tozero',
...valueAxis(catalog.categories.map((c) => counted(r, c.code))),
},
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
},
};
}
const TEA_SEXES = [
{ code: 'male', color: '#4269C2' },
{ code: 'female', color: ROSE },
];
const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ageBands(cells: Reading['strata'][string]): string[] {
const bands = Object.keys(cells)
.map((key) => key.split('|'))
.filter(([, code]) => TEA_SEXES.some((sex) => sex.code === code))
.map(([band]) => band);
return [...new Set(bands)].sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
}
export function ageStack(r: Reading, names: [string, string]): Figure {
const cells = r.strata['age_sex'] ?? {};
const bands = ageBands(cells);
const x = bands.map(ageLabel);
return {
data: TEA_SEXES.flatMap(({ code, color }) => {
const rows = bands.map((band) => cells[`${band}|${code}`]);
const confirmed = rows.map((row) => row?.['numerator'] ?? 0);
const totals = rows.map((row) => row?.['denominator'] ?? 0);
return [confirmed, totals.map((n, i) => n - confirmed[i])].map((y, i) => ({
type: 'bar',
name: `${name(code)} · ${names[i]}`,
offsetgroup: code,
x,
y,
marker: { color: i ? rgba(color, 0.25) : color },
text: y.map((n, j) => (n ? `${n} (${percent((100 * n) / totals[j])} %)` : '')),
textposition: 'inside',
hovertemplate: '%{x}<br>%{fullData.name}: %{y:d} pacientes<extra></extra>',
})) as Partial<Plotly.Data>[];
}),
layout: {
barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: {
title: { text: 'Pacientes' },
rangemode: 'tozero',
...valueAxis(
bands.flatMap((band) =>
TEA_SEXES.map(({ code }) => cells[`${band}|${code}`]?.['denominator'] ?? 0),
),
),
},
},
};
}
export function ageShare(r: Reading, axis: string): Figure {
const cells = r.strata['age_sex'] ?? {};
const bands = ageBands(cells);
const x = bands.map(ageLabel);
return {
data: TEA_SEXES.map(({ code, color }) => {
const rows = bands.map((band) => cells[`${band}|${code}`]);
const shares = rows.map((row) =>
row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null,
);
return {
type: 'bar',
name: name(code),
x,
y: shares,
marker: { color },
text: shares.map((share, i) =>
share === null
? ''
: `${percent(share)} % (${rows[i]['numerator'] ?? 0}/${rows[i]['denominator']})`,
),
textposition: 'outside',
hovertemplate: '%{x}: %{text}<extra>%{fullData.name}</extra>',
};
}),
layout: {
barmode: 'group',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ...percentAxis },
},
};
}
export function valueAxis(values: Iterable<number | null | undefined>) {
const found = [...values].filter((v): v is number => v != null && Number.isFinite(v));
const counts = found.every(Number.isInteger);
const narrow = found.length > 0 && Math.max(...found) - Math.min(0, ...found) <= 5;
return {
type: 'linear' as const,
tickformat: counts ? 'd' : SIGNIFICANT,
hoverformat: counts ? 'd' : '.3~r',
...(counts && narrow ? { dtick: 1 } : {}),
};
}
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string, values: (number | null)[]) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y }, ...valueAxis(values) },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
const data = named.map((c) => ({
type: 'bar' as const,
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
}));
const totals = x.map((_, i) => data.reduce((sum, trace) => sum + trace.y[i], 0));
return {
data,
layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' },
};
}
if (panel.kind === 'rate') {
const lines = [
{ name: 'Total', color: line, at: (r?: Reading) => r?.score },
...TEA_SEXES.map(({ code, color }) => ({
name: name(code),
color,
at: (r?: Reading) => r?.rates?.['sex']?.[code],
})),
];
const data = lines.map(({ name: label, color, at }) => ({
x,
y: series.map((s) => at(s.r) ?? null),
mode: 'lines+markers' as const,
name: label,
line: { color },
marker: { color },
}));
return {
data,
layout: layout(
panel.axis ?? '',
data.flatMap((d) => d.y),
),
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
const band = [
...series.map((s) => at(s.r?.high)),
...[...series].reverse().map((s) => at(s.r?.low)),
];
const scores = series.map((s) => at(s.r?.score));
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: band,
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: scores,
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días', [...band, ...scores]),
};
}
export function sexCountBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const base = countBars(r, catalog, axis, period);
const cells = r.strata['sex-category'] ?? {};
return {
data: TEA_SEXES.map(({ code, color }) => ({
...base.data[0],
name: name(code),
marker: { color },
x: catalog.categories.map((c) => cells[`${code}|${c.code}`]?.['initial-population'] ?? 0),
hovertemplate: '%{y}: %{x:d}<extra>%{fullData.name}</extra>',
})) as Partial<Plotly.Data>[],
layout: { ...base.layout, barmode: 'group', showlegend: true },
};
}
const STOPPED = '#888888';
export function teaSankey(r: Reading): Figure {
const [mchat, psychology, neuro, eeg] = [
'mchat_only',
'psychology',
'neuropediatrics',
'eeg',
].map((code) => counted(r, code));
const nodes = [
{ label: 'M-CHAT', color: '#B8433A', value: mchat + psychology + neuro + eeg },
{ label: 'Evaluación<br>psicológica', color: '#D0B778', value: psychology + neuro + eeg },
{ label: 'Evaluación<br>neuropediátrica', color: '#7184A2', value: neuro + eeg },
{ label: 'EEG de<br>buena calidad', color: OLIVE, value: eeg },
{ label: 'Se quedó en evaluación<br>neuropediátrica', color: STOPPED, value: neuro },
{ label: 'Se quedó en evaluación<br>psicológica', color: STOPPED, value: psychology },
{ label: 'Se quedó en M-CHAT', color: STOPPED, value: mchat },
];
const shown = nodes.flatMap((node, index) => (node.value > 0 ? [index] : []));
const position = new Map(shown.map((index, place) => [index, place]));
const flows: [number, number][] = [
[0, 1],
[0, 6],
[1, 2],
[1, 5],
[2, 3],
[2, 4],
];
const links = flows.flatMap(([source, target]) =>
nodes[target].value > 0
? [{ source: position.get(source)!, target: position.get(target)!, index: target }]
: [],
);
const hovertemplate = '%{label}<br>%{value} pacientes<extra></extra>';
return {
data: [
{
type: 'sankey',
arrangement: 'fixed',
node: {
label: shown.map((index) => `${nodes[index].label} · ${count(nodes[index].value)}`),
color: shown.map((index) => nodes[index].color),
pad: 36,
hovertemplate,
},
link: {
source: links.map(({ source }) => source),
target: links.map(({ target }) => target),
value: links.map(({ index }) => nodes[index].value),
color: links.map(({ index }) => rgba(nodes[index].color, 0.45)),
label: links.map(({ index }) => nodes[index].label.replace('<br>', ' ')),
hovertemplate,
},
} as Partial<Plotly.Data>,
],
layout: { font: { size: 12 }, margin: { l: 20, r: 20, t: 24, b: 24 } },
};
}
const RATE_UNIT = 'por 10 000 niños';
const perTenThousand = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 1 });
function prevalenceCounts(r: Reading, sex?: string): { confirmed: number; total: number } {
if (!sex) {
return { confirmed: counted(r, 'confirmed'), total: r.populations['initial-population'] ?? 0 };
}
return {
confirmed: r.strata['sex-category']?.[`${sex}|confirmed`]?.['initial-population'] ?? 0,
total: r.strata['sex']?.[sex]?.['initial-population'] ?? 0,
};
}
export function prevalenceHeadline(r: Reading, sex?: string) {
const found = sex ? r.rates?.['sex']?.[sex] : r.score;
if (found === undefined) return undefined;
const { confirmed, total } = prevalenceCounts(r, sex);
return {
value: perTenThousand(found),
detail: `${RATE_UNIT} · ${count(confirmed)} confirmados de ${count(total)} niños`,
};
}
export function teaSexBars(r: Reading, selectedSex?: string): Figure {
const x = TEA_SEXES.map(({ code }) => name(code));
const y = TEA_SEXES.map(({ code }) => r.rates?.['sex']?.[code] ?? 0);
return {
data: [
{
type: 'bar',
name: 'Prevalencia registrada',
x,
y,
marker: {
color: TEA_SEXES.map(({ color }) => color),
line: {
color: '#000000',
width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)),
},
},
text: y.map((value) => perTenThousand(value)),
textposition: 'outside',
cliponaxis: false,
customdata: TEA_SEXES.map(({ code }) => {
const { confirmed, total } = prevalenceCounts(r, code);
return [confirmed, total];
}),
hovertemplate: `%{x}<br>%{text} ${RATE_UNIT}<br>%{customdata[0]} confirmados de %{customdata[1]} niños<extra></extra>`,
},
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Sexo' }, type: 'category' },
yaxis: {
title: { text: 'Casos por 10 000 niños' },
rangemode: 'tozero',
...valueAxis(y),
},
},
};
}
export function teaAlterations(r: Reading): Figure {
const rows = [['', r.populations] as const, ...Object.entries(r.strata['alteration'] ?? {})];
const customdata = rows.map(([, c]) => [c['numerator'], c['denominator']]);
const rates = customdata.map(([n, total]) => (total ? (100 * n) / total : 0));
return {
data: [
{
type: 'bar',
x: rows.map(([code]) => (code ? name(code) : 'Alguna alteración')),
y: rates,
marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) },
text: rates.map((rate) => `${percent(rate)} %`),
textposition: 'outside',
cliponaxis: false,
customdata,
hovertemplate:
'%{x}<br>%{text} (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
xaxis: { type: 'category', title: { text: 'Alteración del EEG' } },
yaxis: {
range: [0, 100],
...percentAxis,
title: { text: '% de niños con EEG de buena calidad' },
},
},
};
}