SPB Git

Repository Public

scales.ts 8.8 KB 148 lines typescript

1/**2 * Chart geometry: scales, "nice" ticks and margins. Pure (d3-scale only), shared by ChartSvg and the unit tests.3 * Nothing here invents data: the domain comes from the points (and the optional axis min/max), the marks are drawn4 * exactly where the points are.5 */6import { scaleBand, scaleLinear, scaleLog } from "d3-scale";7import { extent } from "d3-array";8import type { Locale } from "@/schema";9import { formatNumber } from "../i18n";10import { measureText } from "../diagram/text-measure";11import type { ChartSpec } from "./types";1213export interface Tick { pos: number; value: number | string; label: string }14export interface XAxisGeom {15  type: "band" | "number";16  /** Pixel x of a value (band centre on a band axis); null when it cannot be drawn (unknown category, ≤ 0 on a log axis). */17  position: (x: number | string) => number | null;18  /** Width of one band (0 on a numeric axis). */19  bandwidth: number;20  ticks: Tick[];21  domain: [number, number] | string[];22}23export interface YAxisGeom {24  position: (y: number) => number | null;25  ticks: Tick[];26  domain: [number, number];27  /** Pixel y the bars and areas grow from (zero when it is in the domain, the bottom of the plot otherwise). */28  baseline: number;29}30export interface Plot { left: number; top: number; right: number; bottom: number; width: number; height: number }31export interface ChartGeometry { plot: Plot; x: XAxisGeom; y: YAxisGeom; compact: boolean; histogramBinWidth: number | null }3233export const TICK_FONT = 11.5;3435/** Ticks of a linear domain at "nice" round values; the returned domain is widened to those values. */36export function niceLinear(min: number, max: number, count: number): { domain: [number, number]; ticks: number[] } {37  let lo = min, hi = max;38  if (lo === hi) { const pad = lo === 0 ? 1 : Math.abs(lo) * 0.1; lo -= pad; hi += pad; }39  const s = scaleLinear().domain([lo, hi]).nice(count);40  const d = s.domain();41  return { domain: [d[0], d[1]], ticks: s.ticks(count) };42}4344export function niceLog(min: number, max: number): { domain: [number, number]; ticks: number[] } {45  let lo = min, hi = max;46  if (lo === hi) { lo /= 2; hi *= 2; }47  const s = scaleLog().domain([lo, hi]).nice();48  const d = s.domain();49  let ticks = s.ticks(6);50  if (ticks.length > 8) { const powers = ticks.filter((v) => Math.abs(Math.log10(v) - Math.round(Math.log10(v))) < 1e-9); if (powers.length >= 2) ticks = powers; }51  return { domain: [d[0], d[1]], ticks };52}5354const asNumber = (x: number | string): number | null => { if (typeof x === "number") return x; const n = Number(x); return x.trim() !== "" && Number.isFinite(n) ? n : null; };5556export function chartGeometry(chart: ChartSpec, width: number, height: number, locale: Locale, topReserve = 0): ChartGeometry {57  const compact = width < 480;58  const xLog = chart.x.scale === "log" && chart.x.type === "number";59  const yLog = chart.y.scale === "log";60  const points = chart.series.flatMap((s) => s.points);61  const bandAxis = chart.x.type === "category" || chart.kind === "bar";6263  // ── y domain ──64  const yValues: number[] = [];65  for (const p of points) { yValues.push(p.y); if (p.lo !== undefined) yValues.push(p.lo); if (p.hi !== undefined) yValues.push(p.hi); }66  for (const a of chart.annotations ?? []) if (a.y !== undefined) yValues.push(a.y);67  const usable = yLog ? yValues.filter((v) => v > 0) : yValues;68  let [yMin, yMax] = extent(usable) as [number | undefined, number | undefined];69  if (yMin === undefined || yMax === undefined) { yMin = yLog ? 1 : 0; yMax = yLog ? 10 : 1; }70  const zeroBased = !yLog && (chart.kind === "bar" || chart.kind === "histogram" || chart.kind === "area");71  if (zeroBased) { yMin = Math.min(0, yMin); yMax = Math.max(0, yMax); }72  if (chart.y.min !== undefined && (!yLog || chart.y.min > 0)) yMin = chart.y.min;73  if (chart.y.max !== undefined && (!yLog || chart.y.max > 0)) yMax = chart.y.max;74  if (yMin > yMax) [yMin, yMax] = [yMax, yMin];75  const yTickCount = height < 300 ? 4 : 6;76  const yNice = yLog ? niceLog(yMin, yMax) : niceLinear(yMin, yMax, yTickCount);77  // An explicit bound is kept as given; only free bounds are widened to a round value.78  const yDomain: [number, number] = [chart.y.min !== undefined && yMin === chart.y.min ? chart.y.min : yNice.domain[0], chart.y.max !== undefined && yMax === chart.y.max ? chart.y.max : yNice.domain[1]];79  const yTickValues = yNice.ticks.filter((v) => v >= yDomain[0] - 1e-12 && v <= yDomain[1] + 1e-12);80  const yLabels = yTickValues.map((v) => formatNumber(v, locale));8182  // ── margins ──83  const yLabelWidth = yLabels.reduce((m, l) => Math.max(m, measureText(l, TICK_FONT)), 0);84  const left = Math.ceil(yLabelWidth + 10 + 22);85  const right = 14;86  const top = 12 + topReserve;87  const bottom = 22 + 26;88  const plot: Plot = { left, top, right: width - right, bottom: height - bottom, width: Math.max(10, width - left - right), height: Math.max(10, height - top - bottom) };8990  const yScale = (yLog ? scaleLog() : scaleLinear()).domain(yDomain).range([plot.bottom, plot.top]);91  const yPos = (v: number): number | null => (yLog && v <= 0 ? null : Number.isFinite(yScale(v)) ? yScale(v) : null);92  const zero = !yLog && yDomain[0] <= 0 && yDomain[1] >= 0 ? yScale(0) : plot.bottom;93  const y: YAxisGeom = { position: yPos, domain: yDomain, baseline: zero, ticks: yTickValues.map((v, i) => ({ pos: yScale(v), value: v, label: yLabels[i] })) };9495  // ── x ──96  let x: XAxisGeom;97  let histogramBinWidth: number | null = null;98  if (bandAxis) {99    let keys: string[]; let labels: string[];100    if (chart.x.type === "category") {101      keys = []; for (const p of points) { const k = String(p.x); if (!keys.includes(k)) keys.push(k); }102      labels = keys;103    } else {104      const nums = Array.from(new Set(points.map((p) => asNumber(p.x)).filter((v): v is number => v !== null))).sort((a, b) => a - b);105      keys = nums.map(String); labels = nums.map((v) => formatNumber(v, locale));106    }107    const band = scaleBand<string>().domain(keys).range([plot.left, plot.right]).paddingInner(chart.kind === "bar" ? 0.24 : 0.1).paddingOuter(chart.kind === "bar" ? 0.14 : 0.3);108    const bw = band.bandwidth();109    const key = (v: number | string): string => (chart.x.type === "category" ? String(v) : String(asNumber(v)));110    const every = Math.max(1, Math.ceil(keys.length / Math.max(1, Math.floor(plot.width / (compact ? 44 : 56)))));111    x = {112      type: "band", bandwidth: bw, domain: keys,113      position: (v) => { const p = band(key(v)); return p === undefined ? null : p + bw / 2; },114      ticks: keys.map((k, i) => ({ pos: (band(k) ?? 0) + bw / 2, value: k, label: labels[i] })).filter((_, i) => i % every === 0),115    };116  } else {117    const xs = points.map((p) => asNumber(p.x)).filter((v): v is number => v !== null && (!xLog || v > 0));118    for (const a of chart.annotations ?? []) { const v = a.x !== undefined ? asNumber(a.x) : null; if (v !== null && (!xLog || v > 0)) xs.push(v); }119    let [xMin, xMax] = extent(xs) as [number | undefined, number | undefined];120    if (xMin === undefined || xMax === undefined) { xMin = xLog ? 1 : 0; xMax = xLog ? 10 : 1; }121    if (chart.kind === "histogram" && !xLog) {122      const centres = Array.from(new Set(xs)).sort((a, b) => a - b);123      let bw = Infinity;124      for (let i = 1; i < centres.length; i++) bw = Math.min(bw, centres[i] - centres[i - 1]);125      if (!Number.isFinite(bw) || bw <= 0) bw = Math.abs(xMin) > 0 ? Math.abs(xMin) * 0.2 : 1;126      histogramBinWidth = bw; xMin -= bw / 2; xMax += bw / 2;127    }128    const explicitMin = chart.x.min !== undefined && (!xLog || chart.x.min > 0), explicitMax = chart.x.max !== undefined && (!xLog || chart.x.max > 0);129    if (explicitMin) xMin = chart.x.min as number;130    if (explicitMax) xMax = chart.x.max as number;131    if (xMin > xMax) [xMin, xMax] = [xMax, xMin];132    const count = compact ? 4 : 7;133    const nice = xLog ? niceLog(xMin, xMax) : niceLinear(xMin, xMax, count);134    // Lines, areas and histograms span the data exactly; scatter plots get round bounds so points do not sit on the frame.135    const tight = !xLog && chart.kind !== "scatter" && xMin !== xMax;136    const domain: [number, number] = [explicitMin || tight ? xMin : nice.domain[0], explicitMax || tight ? xMax : nice.domain[1]];137    const scale = (xLog ? scaleLog() : scaleLinear()).domain(domain).range([plot.left, plot.right]);138    const tickValues = (tight ? scaleLinear().domain(domain).ticks(count) : nice.ticks).filter((v) => v >= domain[0] - 1e-12 && v <= domain[1] + 1e-12);139    x = {140      type: "number", bandwidth: 0, domain,141      position: (v) => { const n = asNumber(v); if (n === null || (xLog && n <= 0)) return null; const p = scale(n); return Number.isFinite(p) ? p : null; },142      ticks: tickValues.map((v) => ({ pos: scale(v), value: v, label: formatNumber(v, locale) })),143    };144    if (histogramBinWidth !== null) histogramBinWidth = Math.abs(scale(domain[0] + histogramBinWidth) - scale(domain[0]));145  }146  return { plot, x, y, compact, histogramBinWidth };147}148
Files main
Menu

Theme