Headroom reads bar traces through a local shape; Plotly types export no PlotData here
This commit is contained in:
@@ -4,12 +4,20 @@ export const HEADROOM = 1.15;
|
|||||||
|
|
||||||
const AXES = ['xaxis', 'yaxis'] as const;
|
const AXES = ['xaxis', 'yaxis'] as const;
|
||||||
|
|
||||||
|
interface BarTrace {
|
||||||
|
type?: string;
|
||||||
|
textposition?: unknown;
|
||||||
|
orientation?: string;
|
||||||
|
x?: unknown;
|
||||||
|
y?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
export function headroom(
|
export function headroom(
|
||||||
data: Partial<Plotly.Data>[],
|
data: Partial<Plotly.Data>[],
|
||||||
layout: Partial<Plotly.Layout>,
|
layout: Partial<Plotly.Layout>,
|
||||||
): Partial<Plotly.Layout> {
|
): Partial<Plotly.Layout> {
|
||||||
const labelled: Record<(typeof AXES)[number], number[]> = { xaxis: [], yaxis: [] };
|
const labelled: Record<(typeof AXES)[number], number[]> = { xaxis: [], yaxis: [] };
|
||||||
for (const trace of data as Partial<Plotly.PlotData>[]) {
|
for (const trace of data as BarTrace[]) {
|
||||||
if (trace.type !== 'bar' || trace.textposition !== 'outside') continue;
|
if (trace.type !== 'bar' || trace.textposition !== 'outside') continue;
|
||||||
const horizontal = trace.orientation === 'h';
|
const horizontal = trace.orientation === 'h';
|
||||||
const values = ((horizontal ? trace.x : trace.y) ?? []) as unknown[];
|
const values = ((horizontal ? trace.x : trace.y) ?? []) as unknown[];
|
||||||
@@ -17,15 +25,15 @@ export function headroom(
|
|||||||
...values.filter((v): v is number => typeof v === 'number' && Number.isFinite(v)),
|
...values.filter((v): v is number => typeof v === 'number' && Number.isFinite(v)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Object.fromEntries(
|
const room: Partial<Plotly.Layout> = {};
|
||||||
AXES.flatMap((key) => {
|
for (const key of AXES) {
|
||||||
const values = labelled[key];
|
const values = labelled[key];
|
||||||
const axis = layout[key];
|
const axis = layout[key];
|
||||||
if (!values.length || axis?.range) return [];
|
if (!values.length || axis?.range) continue;
|
||||||
const low = Math.min(0, ...values);
|
const low = Math.min(0, ...values);
|
||||||
const high = Math.max(0, ...values);
|
const high = Math.max(0, ...values);
|
||||||
if (low === high) return [];
|
if (low === high) continue;
|
||||||
return [[key, { ...axis, range: [low * HEADROOM, high * HEADROOM] as [number, number] }]];
|
room[key] = { ...axis, range: [low * HEADROOM, high * HEADROOM] };
|
||||||
}),
|
}
|
||||||
);
|
return room;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user