diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index f68e2e4..758a275 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -13,7 +13,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities'; import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown'; import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; -import { C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; +import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; @@ -253,7 +253,7 @@ export class IndicadorFigurePanel implements OnChanges { const adapted = c1DonutFigure(data, selection); if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState; return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes, - donutLegend: adapted.legend, ownLayout: true, + donutLegend: adapted.legend.length ? adapted.legend : undefined, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined, emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined }; })); } diff --git a/src/app/features/indicadores/indicadores-c1-donut.spec.ts b/src/app/features/indicadores/indicadores-c1-donut.spec.ts index bd9b762..73fe78b 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.spec.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.spec.ts @@ -14,8 +14,10 @@ const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-3 const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; describe('Dona de dos anillos para C1', () => { - it('solo aplica a C1 con fig_c1_donas', () => { + it('solo aplica a C1 con las figuras por grupo de edad', () => { expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true); + expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true); + expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true); expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false); expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false); }); @@ -41,6 +43,26 @@ describe('Dona de dos anillos para C1', () => { expect(result.legend.map(e => e.label)).toEqual(['Con EEG', 'Sin EEG', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' }); }); + it('dona por grupo de edad: sin anillo interior y con el porcentaje total al centro', () => { + const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' }); + if (result.status !== 'supported') throw new Error(result.reason); + expect(result.figure.data).toHaveLength(1); + const [ring] = result.figure.data as { labels: string[]; values: number[] }[]; + expect(ring.values).toEqual([16, 13, 17, 8, 5, 5]); + expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('71.9 %'); + expect(result.legend.map(e => e.label)).toEqual(['Con EEG', 'Sin EEG', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); + }); + it('barras por grupo de edad: una barra por grupo con su porcentaje', () => { + const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' }, + { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' }); + if (result.status !== 'supported') throw new Error(result.reason); + const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[]; + expect(bars.type).toBe('bar'); + expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); + expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']); + expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG'); + expect(result.legend).toEqual([]); + }); it('usa etiquetas propias por indicador y neutrales para otros', () => { expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Con diagnóstico positivo de TEA', 'Sin diagnóstico de TEA']); expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']); diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts index 0da279c..a7142e5 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -1,12 +1,18 @@ import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario'; import { percentNumber, shareText } from './indicadores-format'; import { DonutLegendEntry } from './indicadores-donut-drilldown'; +import { c2Theme } from './indicadores-c2-palette'; import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; -// Double donut for a C1 proportion over one semester, drawn like CaCu's «Distribución de resultados -// citológicos»: the inner ring splits the denominator into patients with and without the event, the -// outer ring splits each of them by age group. Built from the age-stratified C1 rows. +// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows: +// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring +// splits the denominator into patients with and without the event, the outer ring each of them by age group. +// - fig_c1_dona_edad: only that outer ring, with the overall percentage in the centre. +// - fig_c1_barras_edad: one bar per age group with its percentage. export const C1_DONUT = 'fig_c1_donas'; +export const C1_RING = 'fig_c1_dona_edad'; +export const C1_AGE_BARS = 'fig_c1_barras_edad'; +const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS]; export const C1_DONUT_ESTRATO = 'grupo_edad'; // Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording. const EVENT_LABELS: Readonly> = { @@ -20,7 +26,7 @@ const RING_COLORS = ['#2F6DB3', '#D9822B'] as const; export type C1DonutResult = { status: 'unsupported'; reason: string } | { status: 'supported'; figure: PlotlyFigure; legend: DonutLegendEntry[]; total: number; notes: string[] }; export function c1DonutCapability(contract: string, representation: string): boolean { - return contract === 'C1' && representation === C1_DONUT; + return contract === 'C1' && C1_AGE_FIGURES.includes(representation); } export function c1DonutLabels(indicador: string): readonly [string, string] { return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento']; @@ -53,6 +59,15 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): || !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables'); const labels = c1DonutLabels(data.id); + const notes = Array.isArray(data.notas) ? [...data.notas] : []; + const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period }; + const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0); + if (selection.figura === C1_AGE_BARS) { + const figure = ageBars(strata, labels[0], selection); + figure.layout = { ...figure.layout, title }; + return { status: 'supported', figure, legend: [], total, notes }; + } + const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] })); const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {}; grupos.forEach((g, gi) => strata.forEach((s, i) => { @@ -61,8 +76,6 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id }); celdas[id] = { n, estado: 'Publicado' }; })); - const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0); - const notes = Array.isArray(data.notas) ? [...data.notas] : []; const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' }, escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' }; const figure = dona(modelo, {}, selection.tema); @@ -78,10 +91,34 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): const n = (inner['values'] as number[])[i]; return n / total < .05 ? '' : escape(g.etiqueta) + '
' + percentNumber(100 * n / total) + ' %'; }); + if (selection.figura === C1_RING) { + // Only the outer ring, wider, around the overall percentage of the event. + const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0); + figure.data = [{ ...outer, hole: .6 }]; + figure.layout = { ...figure.layout, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, + text: '' + percentNumber(100 * numerador / total) + ' %', font: { size: 26, color: c2Theme(selection.tema).text } }] }; + } } - figure.layout = { ...figure.layout, title: { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period } }; - // Both rings, then the age groups in the shades of the first ring. + figure.layout = { ...figure.layout, title }; + // Both groups, then the age groups in the shades of the first one. const legend = [...grupos.map(g => ({ label: g.etiqueta, color: g.color })), ...strata.map((s, i) => ({ label: s.label, color: categorias[i].color }))]; return { status: 'supported', figure, legend, total, notes }; } + +// One bar per age group: the share of its patients with the event. +function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure { + const theme = c2Theme(selection.tema); + const x = strata.map(s => escape(s.label)); + const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null); + const what = event.charAt(0).toLowerCase() + event.slice(1); + return { data: [{ type: 'bar', x, y, marker: { color: RING_COLORS[0], line: { color: theme.background, width: 1 } }, + text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false, + customdata: strata.map(s => [s.numerador, s.denominador]), + hovertemplate: '%{x}
%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)' }], + layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false, + paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true }, + yaxis: { title: { text: '% de pacientes ' + escape(what) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } }, + config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index 4ac5d04..c7ec47f 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -2,6 +2,8 @@ // Exact IDs remain the option values and HTTP identities; never infer a type // from a prefix. Unknown options keep a neutral label in publication order. const FIGURE_LABELS: Readonly> = { + fig_c1_barras_edad: 'Barras por grupo de edad', + fig_c1_dona_edad: 'Dona por grupo de edad', fig_c1_donas: 'Dona de dos anillos', fig_c1_grupos: 'Grupos', fig_c1_puntos: 'Puntos',