Files
WebApp/src/app/indicadores/figures.ts
T
alberto d8b9452870 F2c: risk page after the 3 Dec review
Replace the risk introduction with the reviewed text, name severe ADOS-2
probabilities in the risk section and record table, and place the TEA
clarification below the risk probability table through section content.
Use one shared decimal log-axis builder in the patient forest and both
governance OR charts. Add builder and patient logic coverage and update
the page case for the section, column headers and clarification.

Choices left open by the spec:
- Name the builder logAxis and mirror valueAxis's iterable input signature;
  put its logic spec in indicadores/figures.spec.ts beside the builder.
- Generate the 1-2-3-5-7 sequence from the floor of the minimum log10 to
  the ceiling of the maximum log10, including only 1 in the last decade.
  Whole-decade bounds retain labels for narrow and single-value ranges.
- Ignore missing, nonfinite and nonpositive input; return empty tick
  arrays when no positive finite data remain. Discard generated zero or
  nonfinite ticks at floating-point limits.
- Construct tick values from decimal exponent strings to avoid binary
  multiplication artifacts; use explicit array ticks and SHORT hovers.
- Let the existing private decimal formatter accept optional Intl options,
  retaining its existing defaults. For log labels use its es-MX locale,
  one significant digit and no grouping, preserving small decimals and
  avoiding scientific notation and trailing zeros.
- Include estimates and confidence bounds in each chart's input, plus 1
  in the two charts that draw the reference line.
- Represent the risk table note as a following text block so the existing
  page and PDF renderers both place it below the table.
- Cover decimal sequences, whole-decade bounds, singleton and iterable
  input, invalid input, small and large labels, patient confidence bounds,
  probability labels and the clarification's PDF inclusion in logic tests.
  Add page assertions for the probability headers and clarification.

Validation: ruff check . passed; ruff format --check . passed (144 files);
git diff --check passed. A Node smoke check of the source logAxis function
passed nine assertions. Prettier was skipped because this worktree has no
WebApp/node_modules/.bin/prettier. Angular tests/build and Playwright page
tests were not run here, as the spec reserves them for milkpc/the VM.
Python imports and the API did not change; lint-imports and API generation
were not needed.
2026-12-03 13:50:53 -06:00

690 lines
23 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, options: Intl.NumberFormatOptions = { maximumFractionDigits: 2 }) =>
n.toLocaleString('es-MX', options);
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!;
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)',
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
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 }) => ({
type: 'bar',
name: name(code),
x,
y: bands.map((band) => {
const row = cells[`${band}|${code}`];
return row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null;
}),
marker: { color },
texttemplate: '%{y:.1~f} %',
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1~f} %<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 logAxis(values: Iterable<number | null | undefined>) {
const found = [...values].filter((v): v is number => v != null && Number.isFinite(v) && v > 0);
const tickvals: number[] = [];
if (found.length) {
const first = Math.floor(Math.log10(Math.min(...found)));
const last = Math.ceil(Math.log10(Math.max(...found)));
for (let decade = first; decade <= last; decade++) {
for (const multiplier of [1, 2, 3, 5, 7]) {
if (decade === last && multiplier > 1) continue;
const value = Number(`${multiplier}e${decade}`);
if (value > 0 && Number.isFinite(value)) tickvals.push(value);
}
}
}
return {
type: 'log' as const,
tickmode: 'array' as const,
tickvals,
ticktext: tickvals.map((v) => decimal(v, { maximumSignificantDigits: 1, useGrouping: false })),
hoverformat: SHORT,
};
}
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' },
};
}
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),
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 } },
};
}
export function teaSexBars(r: Reading, selectedSex?: string): Figure {
const cells = r.strata['sex-category'] ?? {};
const x = TEA_SEXES.map(({ code }) => name(code));
return {
data: [
{ code: 'confirmed', label: 'Diagnóstico confirmado' },
{ code: 'in_population', label: 'Sin diagnóstico confirmado' },
].map(({ code: category, label }, i) => {
const y = TEA_SEXES.map(
({ code }) => cells[`${code}|${category}`]?.['initial-population'] ?? 0,
);
return {
type: 'bar',
name: label,
x,
y,
marker: {
color: TEA_SEXES.map(({ color }) => (i ? rgba(color, 0.25) : color)),
line: {
color: TEA_SEXES.map(({ color }) => color),
width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)),
},
},
customdata: TEA_SEXES.map(({ code }, j) => {
const total = r.strata['sex']?.[code]?.['initial-population'] ?? 0;
return [percent(total ? (100 * y[j]) / total : 0), total];
}),
hovertemplate:
'%{x} · %{fullData.name}<br>%{y:d} niños, %{customdata[0]} % de %{customdata[1]}<extra></extra>',
};
}),
layout: {
barmode: 'group',
xaxis: { title: { text: 'Sexo' }, type: 'category' },
yaxis: {
title: { text: 'Niños' },
rangemode: 'tozero',
...valueAxis(
TEA_SEXES.map(({ code }) => r.strata['sex']?.[code]?.['initial-population'] ?? 0),
),
},
},
};
}
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' },
},
},
};
}