Files
WebApp/src/app/plot-headroom.ts
T

40 lines
1.2 KiB
TypeScript

import type * as Plotly from 'plotly.js';
export const HEADROOM = 1.15;
const AXES = ['xaxis', 'yaxis'] as const;
interface BarTrace {
type?: string;
textposition?: unknown;
orientation?: string;
x?: unknown;
y?: unknown;
}
export function headroom(
data: Partial<Plotly.Data>[],
layout: Partial<Plotly.Layout>,
): Partial<Plotly.Layout> {
const labelled: Record<(typeof AXES)[number], number[]> = { xaxis: [], yaxis: [] };
for (const trace of data as BarTrace[]) {
if (trace.type !== 'bar' || trace.textposition !== 'outside') continue;
const horizontal = trace.orientation === 'h';
const values = ((horizontal ? trace.x : trace.y) ?? []) as unknown[];
labelled[horizontal ? 'xaxis' : 'yaxis'].push(
...values.filter((v): v is number => typeof v === 'number' && Number.isFinite(v)),
);
}
const room: Partial<Plotly.Layout> = {};
for (const key of AXES) {
const values = labelled[key];
const axis = layout[key];
if (!values.length || axis?.range) continue;
const low = Math.min(0, ...values);
const high = Math.max(0, ...values);
if (low === high) continue;
room[key] = { ...axis, range: [low * HEADROOM, high * HEADROOM] };
}
return room;
}