F4: TEA indicators display after review

- Prevalencia registrada (M31): the sex selector, its signal and the bar outline highlight are gone; the headline always shows the total rate and the bars keep one bar per sex
- Indicadores de oportunidad: the box charts show Q3, Mediana and Q1 in the hover, formatted with the shared one-decimal hover format, instead of annotations
- Porcentaje de confirmacion diagnostica (M24): the stacked bars, axis title, ticks, bar text and hover are in percent of the patients of each sex and age group
- Porcentaje de pacientes con / sin EEG (M21, M22): bar text shows the percentage only
- Headroom: the shared percent axis now ends at 110 with ticks every 20, and the shared plot builder never clips bar labels (cliponaxis false for every bar trace), so a 100 % bar keeps its label; the per-trace cliponaxis on the bar builders was removed
- Indicadores clinicos: route, grid and figure-row charts all use one height (430 px, was 300/320/360)

Choices: percent axis headroom lives in percentAxis, with rate dots keeping their own 0-100 range; the clinical height is a single component constant.
This commit is contained in:
2026-12-03 17:02:21 -06:00
parent dca39203d2
commit 3154ba92df
5 changed files with 78 additions and 98 deletions
+22 -53
View File
@@ -11,6 +11,8 @@ export const percentAxis = {
ticksuffix: ' %', ticksuffix: ' %',
tickformat: '.0f', tickformat: '.0f',
hoverformat: SHORT, hoverformat: SHORT,
range: [0, 110],
dtick: 20,
}; };
const count = (n: number) => n.toLocaleString('es-MX'); const count = (n: number) => n.toLocaleString('es-MX');
@@ -231,7 +233,7 @@ export function rateDots(
categoryarray: [...y].reverse(), categoryarray: [...y].reverse(),
automargin: true, automargin: true,
}, },
xaxis: { range: [0, 100], ...percentAxis, zeroline: false, title: { text: spec.axis } }, xaxis: { ...percentAxis, range: [0, 100], zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({ annotations: rows.map((x) => ({
x: 1, x: 1,
xref: 'paper', xref: 'paper',
@@ -272,17 +274,6 @@ export function fill(template: string, r: Reading): string {
export function boxFigure(r: Reading, period: string): Figure { export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!; const q1 = r.low ?? r.score!;
const q3 = r.high ?? 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 { return {
data: [ data: [
{ {
@@ -296,16 +287,11 @@ export function boxFigure(r: Reading, period: string): Figure {
upperfence: [q3], upperfence: [q3],
marker: { color: '#4269C2' }, marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)', fillcolor: 'rgba(66,105,194,0.55)',
hoverinfo: 'skip', hovertemplate: `Q3: %{q3:${SHORT}}<br>Mediana: %{median:${SHORT}}<br>Q1: %{q1:${SHORT}}<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
showlegend: false, 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]) }, yaxis: { title: { text: 'días' }, rangemode: 'tozero', ...valueAxis([q1, r.score!, q3]) },
}, },
}; };
@@ -399,32 +385,28 @@ export function ageStack(r: Reading, names: [string, string]): Figure {
return { return {
data: TEA_SEXES.flatMap(({ code, color }) => { data: TEA_SEXES.flatMap(({ code, color }) => {
const rows = bands.map((band) => cells[`${band}|${code}`]); const rows = bands.map((band) => cells[`${band}|${code}`]);
const confirmed = rows.map((row) => row?.['numerator'] ?? 0);
const totals = rows.map((row) => row?.['denominator'] ?? 0); const totals = rows.map((row) => row?.['denominator'] ?? 0);
return [confirmed, totals.map((n, i) => n - confirmed[i])].map((y, i) => ({ const confirmed = rows.map((row, j) =>
totals[j] ? (100 * (row?.['numerator'] ?? 0)) / totals[j] : 0,
);
return [confirmed, totals.map((total, j) => (total ? 100 - confirmed[j] : 0))].map(
(y, i) => ({
type: 'bar', type: 'bar',
name: `${name(code)} · ${names[i]}`, name: `${name(code)} · ${names[i]}`,
offsetgroup: code, offsetgroup: code,
x, x,
y, y,
marker: { color: i ? rgba(color, 0.25) : color }, marker: { color: i ? rgba(color, 0.25) : color },
text: y.map((n, j) => (n ? `${n} (${percent((100 * n) / totals[j])} %)` : '')), text: y.map((share) => (share ? `${percent(share)} %` : '')),
textposition: 'inside', textposition: 'inside',
hovertemplate: '%{x}<br>%{fullData.name}: %{y:d} pacientes<extra></extra>', hovertemplate: `%{x}<br>%{fullData.name}: %{y:${SHORT}} %<extra></extra>`,
})) as Partial<Plotly.Data>[]; }),
) as Partial<Plotly.Data>[];
}), }),
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { yaxis: { title: { text: '% de pacientes' }, ...percentAxis },
title: { text: 'Pacientes' },
rangemode: 'tozero',
...valueAxis(
bands.flatMap((band) =>
TEA_SEXES.map(({ code }) => cells[`${band}|${code}`]?.['denominator'] ?? 0),
),
),
},
}, },
}; };
} }
@@ -445,11 +427,7 @@ export function ageShare(r: Reading, axis: string): Figure {
x, x,
y: shares, y: shares,
marker: { color }, marker: { color },
text: shares.map((share, i) => text: shares.map((share) => (share === null ? '' : `${percent(share)} %`)),
share === null
? ''
: `${percent(share)} % (${rows[i]['numerator'] ?? 0}/${rows[i]['denominator']})`,
),
textposition: 'outside', textposition: 'outside',
hovertemplate: '%{x}: %{text}<extra>%{fullData.name}</extra>', hovertemplate: '%{x}: %{text}<extra>%{fullData.name}</extra>',
}; };
@@ -457,7 +435,7 @@ export function ageShare(r: Reading, axis: string): Figure {
layout: { layout: {
barmode: 'group', barmode: 'group',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' }, xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ...percentAxis }, yaxis: { title: { text: axis }, ...percentAxis },
}, },
}; };
} }
@@ -674,17 +652,16 @@ function prevalenceCounts(r: Reading, sex?: string): { confirmed: number; total:
}; };
} }
export function prevalenceHeadline(r: Reading, sex?: string) { export function prevalenceHeadline(r: Reading) {
const found = sex ? r.rates?.['sex']?.[sex] : r.score; if (r.score === undefined) return undefined;
if (found === undefined) return undefined; const { confirmed, total } = prevalenceCounts(r);
const { confirmed, total } = prevalenceCounts(r, sex);
return { return {
value: perTenThousand(found), value: perTenThousand(r.score),
detail: `${RATE_UNIT} · ${count(confirmed)} confirmados de ${count(total)} niños`, detail: `${RATE_UNIT} · ${count(confirmed)} confirmados de ${count(total)} niños`,
}; };
} }
export function teaSexBars(r: Reading, selectedSex?: string): Figure { export function teaSexBars(r: Reading): Figure {
const x = TEA_SEXES.map(({ code }) => name(code)); const x = TEA_SEXES.map(({ code }) => name(code));
const y = TEA_SEXES.map(({ code }) => r.rates?.['sex']?.[code] ?? 0); const y = TEA_SEXES.map(({ code }) => r.rates?.['sex']?.[code] ?? 0);
return { return {
@@ -694,16 +671,9 @@ export function teaSexBars(r: Reading, selectedSex?: string): Figure {
name: 'Prevalencia registrada', name: 'Prevalencia registrada',
x, x,
y, y,
marker: { marker: { color: TEA_SEXES.map(({ color }) => color) },
color: TEA_SEXES.map(({ color }) => color),
line: {
color: '#000000',
width: TEA_SEXES.map(({ code }) => (code === selectedSex ? 2 : 0)),
},
},
text: y.map((value) => perTenThousand(value)), text: y.map((value) => perTenThousand(value)),
textposition: 'outside', textposition: 'outside',
cliponaxis: false,
customdata: TEA_SEXES.map(({ code }) => { customdata: TEA_SEXES.map(({ code }) => {
const { confirmed, total } = prevalenceCounts(r, code); const { confirmed, total } = prevalenceCounts(r, code);
return [confirmed, total]; return [confirmed, total];
@@ -736,7 +706,6 @@ export function teaAlterations(r: Reading): Figure {
marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) }, marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) },
text: rates.map((rate) => `${percent(rate)} %`), text: rates.map((rate) => `${percent(rate)} %`),
textposition: 'outside', textposition: 'outside',
cliponaxis: false,
customdata, customdata,
hovertemplate: hovertemplate:
'%{x}<br>%{text} (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>', '%{x}<br>%{text} (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>',
+3 -12
View File
@@ -90,7 +90,7 @@
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" /> <app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (routeOf(section); as fig) { } @else if (routeOf(section); as fig) {
<app-plot [figure]="fig" [height]="300" /> <app-plot [figure]="fig" [height]="clinicalHeight" />
} @else { } @else {
<p class="state">Sin tiempos publicados en el periodo.</p> <p class="state">Sin tiempos publicados en el periodo.</p>
} }
@@ -137,15 +137,6 @@
<h2 class="box-title">{{ f.title }}</h2> <h2 class="box-title">{{ f.title }}</h2>
<p class="state">Filtro general aplicado: {{ period }}</p> <p class="state">Filtro general aplicado: {{ period }}</p>
@if (f.kind === 'sex-bars') { @if (f.kind === 'sex-bars') {
<mat-button-toggle-group
aria-label="Sexo"
[value]="prevalenceSex()"
(change)="prevalenceSex.set($event.value)"
>
<mat-button-toggle [value]="undefined">Ambos sexos</mat-button-toggle>
<mat-button-toggle value="female">Femenino</mat-button-toggle>
<mat-button-toggle value="male">Masculino</mat-button-toggle>
</mat-button-toggle-group>
@if (prevalenceOf(f); as p) { @if (prevalenceOf(f); as p) {
<div class="kpi-value"> <div class="kpi-value">
{{ p.value }} {{ p.value }}
@@ -156,7 +147,7 @@
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" /> <app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) { } @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="320" /> <app-plot [figure]="fig" [height]="clinicalHeight" />
} @else { } @else {
<div class="empty-figure">Sin datos publicados</div> <div class="empty-figure">Sin datos publicados</div>
} }
@@ -228,7 +219,7 @@
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" /> <app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) { } @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="360" /> <app-plot [figure]="fig" [height]="clinicalHeight" />
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
+3 -3
View File
@@ -50,7 +50,6 @@ export class TabIndicadores {
protected readonly type = signal<PeriodType>('semester'); protected readonly type = signal<PeriodType>('semester');
protected readonly options = computed(() => periods(this.type())); protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal<string | undefined>(undefined); protected readonly chosen = signal<string | undefined>(undefined);
protected readonly prevalenceSex = signal<string | undefined>(undefined);
protected readonly applied = signal<string | undefined>(undefined); protected readonly applied = signal<string | undefined>(undefined);
protected readonly page = computed(() => PAGES[this.domain()]); protected readonly page = computed(() => PAGES[this.domain()]);
@@ -106,6 +105,7 @@ export class TabIndicadores {
}); });
} }
protected readonly clinicalHeight = 430;
protected readonly pending = 'Indicador no publicado en el catálogo institucional.'; protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
protected setType(type: PeriodType): void { protected setType(type: PeriodType): void {
this.type.set(type); this.type.set(type);
@@ -140,7 +140,7 @@ export class TabIndicadores {
} }
protected prevalenceOf(spec: FigureSpec) { protected prevalenceOf(spec: FigureSpec) {
const r = this.rd(spec.measure); const r = this.rd(spec.measure);
return r ? prevalenceHeadline(r, this.prevalenceSex()) : undefined; return r ? prevalenceHeadline(r) : undefined;
} }
protected readonly teaSummary = computed(() => { protected readonly teaSummary = computed(() => {
const rd = (c: string) => this.loaded()?.get(c); const rd = (c: string) => this.loaded()?.get(c);
@@ -198,7 +198,7 @@ export class TabIndicadores {
case 'sankey': case 'sankey':
return teaSankey(r); return teaSankey(r);
case 'sex-bars': case 'sex-bars':
return teaSexBars(r, this.prevalenceSex()); return teaSexBars(r);
case 'alterations': case 'alterations':
return teaAlterations(r); return teaAlterations(r);
case 'age-stack': case 'age-stack':
+38 -22
View File
@@ -399,14 +399,18 @@ describe('TEA clinical figures', () => {
}); });
}); });
it('annotates only the median and the quartiles on the box', () => { it('shows the quartiles and the median in the hover of the box instead of annotations', () => {
const figure = boxFigure({ populations: {}, strata: {}, score: 12.5, low: 8, high: 20 }, '2025-S1'); const figure = boxFigure(
expect(figure.layout?.annotations?.map((a) => a.text)).toEqual([ { populations: {}, strata: {}, score: 12.5, low: 8, high: 20 },
'Q3 20', '2025-S1',
'Mediana 12.5', );
'Q1 8', expect(figure.layout?.annotations).toBeUndefined();
]); expect(figure.data[0]).toMatchObject({
expect(figure.data[0]).toMatchObject({ hoverinfo: 'skip' }); q1: [8],
median: [12.5],
q3: [20],
hovertemplate: 'Q3: %{q3:.1~f}<br>Mediana: %{median:.1~f}<br>Q1: %{q1:.1~f}<extra></extra>',
});
}); });
const prevalence = { const prevalence = {
@@ -432,7 +436,7 @@ describe('TEA clinical figures', () => {
}; };
it('shows the prevalence rate per 10,000 as the bar text and the counts in the hover', () => { it('shows the prevalence rate per 10,000 as the bar text and the counts in the hover', () => {
const figure = teaSexBars(prevalence, 'female'); const figure = teaSexBars(prevalence);
expect(figure.layout?.barmode).toBeUndefined(); expect(figure.layout?.barmode).toBeUndefined();
expect(figure.data).toHaveLength(1); expect(figure.data).toHaveLength(1);
expect(figure.data[0]).toMatchObject({ expect(figure.data[0]).toMatchObject({
@@ -444,7 +448,7 @@ describe('TEA clinical figures', () => {
[3, 6], [3, 6],
[1, 4], [1, 4],
], ],
marker: { color: ['#4269C2', '#C24269'], line: { width: [0, 2] } }, marker: { color: ['#4269C2', '#C24269'] },
}); });
expect(figure.data[0]).toMatchObject({ expect(figure.data[0]).toMatchObject({
hovertemplate: expect.stringContaining( hovertemplate: expect.stringContaining(
@@ -453,15 +457,11 @@ describe('TEA clinical figures', () => {
}); });
}); });
it('puts the total or the chosen sex rate in the headline', () => { it('puts the total rate in the headline', () => {
expect(prevalenceHeadline(prevalence)).toEqual({ expect(prevalenceHeadline(prevalence)).toEqual({
value: '3,333.3', value: '3,333.3',
detail: 'por 10 000 niños · 4 confirmados de 12 niños', detail: 'por 10 000 niños · 4 confirmados de 12 niños',
}); });
expect(prevalenceHeadline(prevalence, 'male')).toEqual({
value: '5,000',
detail: 'por 10 000 niños · 3 confirmados de 6 niños',
});
expect(prevalenceHeadline({ populations: {}, strata: {} })).toBeUndefined(); expect(prevalenceHeadline({ populations: {}, strata: {} })).toBeUndefined();
}); });
@@ -567,20 +567,36 @@ describe('TEA clinical figures', () => {
}; };
const ageGroups = ['16 a 23 meses', '24 a 36 meses']; const ageGroups = ['16 a 23 meses', '24 a 36 meses'];
it('stacks diagnostic status in one bar per sex in each age group', () => { it('stacks diagnostic status as percentages in one bar per sex in each age group', () => {
const figure = ageStack(byAgeAndSex, ['Confirmados', 'En proceso']); const figure = ageStack(byAgeAndSex, ['Confirmados', 'En proceso']);
expect(figure.layout?.barmode).toBe('stack'); expect(figure.layout?.barmode).toBe('stack');
expect(figure.data).toMatchObject([ expect(figure.data).toMatchObject([
{ x: ageGroups, offsetgroup: 'male', y: [1, 1], marker: { color: '#4269C2' } }, {
{ x: ageGroups, offsetgroup: 'male', y: [3, 0], marker: { color: 'rgba(66,105,194,0.25)' } }, x: ageGroups,
{ x: ageGroups, offsetgroup: 'female', y: [1, 0], marker: { color: '#C24269' } }, offsetgroup: 'male',
y: [25, 100],
text: ['25 %', '100 %'],
marker: { color: '#4269C2' },
},
{
x: ageGroups,
offsetgroup: 'male',
y: [75, 0],
text: ['75 %', ''],
marker: { color: 'rgba(66,105,194,0.25)' },
},
{ x: ageGroups, offsetgroup: 'female', y: [50, 0], marker: { color: '#C24269' } },
{ {
x: ageGroups, x: ageGroups,
offsetgroup: 'female', offsetgroup: 'female',
y: [1, 0], y: [50, 0],
marker: { color: 'rgba(194,66,105,0.25)' }, marker: { color: 'rgba(194,66,105,0.25)' },
}, },
]); ]);
expect(figure.layout?.yaxis).toMatchObject({
title: { text: '% de pacientes' },
ticksuffix: ' %',
});
}); });
it('groups EEG percentages by age and sex and omits missing denominators', () => { it('groups EEG percentages by age and sex and omits missing denominators', () => {
@@ -591,14 +607,14 @@ describe('TEA clinical figures', () => {
name: 'Masculino', name: 'Masculino',
x: ageGroups, x: ageGroups,
y: [25, 100], y: [25, 100],
text: ['25 % (1/4)', '100 % (1/1)'], text: ['25 %', '100 %'],
marker: { color: '#4269C2' }, marker: { color: '#4269C2' },
}, },
{ {
name: 'Femenino', name: 'Femenino',
x: ageGroups, x: ageGroups,
y: [50, null], y: [50, null],
text: ['50 % (1/2)', ''], text: ['50 %', ''],
marker: { color: '#C24269' }, marker: { color: '#C24269' },
}, },
]); ]);
+5 -1
View File
@@ -52,7 +52,11 @@ function layoutOf(layout: Partial<Plotly.Layout> = {}): Partial<Plotly.Layout> {
} }
function withRoom(data: Partial<Plotly.Data>[]): Plotly.Data[] { function withRoom(data: Partial<Plotly.Data>[]): Plotly.Data[] {
return data.map((d) => (d.type === 'pie' ? { automargin: true, ...d } : d)) as Plotly.Data[]; return data.map((d) => {
if (d.type === 'pie') return { automargin: true, ...d };
if (d.type === 'bar') return { cliponaxis: false, ...d };
return d;
}) as Plotly.Data[];
} }
const CONFIG: Partial<Plotly.Config> = { const CONFIG: Partial<Plotly.Config> = {
responsive: true, responsive: true,