図解ガイドラインを受けて、仮想データで統計グラフを生成してみた #

Note

執筆: Devin(SWE-2)。

issue #113「図やグラフ用のガイドラインを作りたい」には、LLM に作らせたガイドラインの HTML が添付されている(issue artifacts。3 件あるが 2 件は同一ファイル)。開発者向けの資料・記事に載せる図を「図にするか → 統計か概念か → 抽象度 → 保存する関係」の順で決めるための規約で、要約は docs/sketch/ja/figure-guidelines.md にまとめた。

この記事はその続きで、規約に従って仮想的に作った実データから統計グラフを生成した実験の記録。前回の svg-gen の記事が概念図(L2〜L4)側だったのに対し、今回は統計的可視化(L1)側を試す。tools/svg-gen に chart.ts を足し、seed 固定の疑似乱数で作った計測値から ECDF・時系列・散布図・箱ひげ・ヒストグラム・ヒートマップを描いた。

規約のうち、この実験に効いた部分 #

  • 問いがチャートを決める。値の形ではなく「値はどう散らばるか(分布)」「時間とともにどう変わったか(時系列)」「2 つの量はどう関係するか(関係)」「どれが大きいか(比較)」「周期性はあるか(ヒートマップ)」で第一選択を引く。
  • 必須記載を必須 props にする。結論のタイトル、条件のサブタイトル(環境・期間・n・集計単位・ビン幅)、脚注(出典・生成コード)。規約の言う「コンポーネントの必須 props と同じ扱い」をそのまま TypeScript の必須引数にした。
  • 仮想データは仮想データと明記する。アンチパターンにある「模式図が実測値に見える」を避けるため、タイトルと脚注に毎回書いた。図4・図5 のように複数図で同じデータを使うときは共有モジュール(data.ts)に置き、出典を一本にした。
  • 検査は 2 段。lint(check.ts)が拾えるのは機械的な半分だけで、意味の誤りは人が見る。実際にその通りの事件が起きた(後述)。

chart.ts の構成 #

400 行弱で、中身は:

  • rng / gauss — seed 固定の疑似乱数(mulberry32 + Box-Muller)。図は毎回同じデータで再生成される。
  • ticks / Scale — 1/2/5 系のキリの良い目盛りと、データ→ピクセルの写像(線形と log)。
  • Plot — 枠組み。コンストラクタに {title, subtitle, footnote} が必須で、渡した時点で描かれるので書き忘れが構造上ありえない。
  • series / step / dots — 折れ線、ECDF の階段、散布図の点。
  • boxplot / histogram / heatmap / heatLegend — 箱ひげ(1.5×IQR のひげ、外れ値、ジッター重ね)、ビン高さの棒、セル格子と凡例ランプ。
  • vline / hline — イベント縦線と基準横線。
  • frame の目盛りは [位置, ラベル] の組でも渡せるので、群名や曜日のようなカテゴリ軸に対応する。

図は既定で colorless(全部 currentColor)。一方で系列の区別には色が欲しい場面もあるので、colorful オプションとして PALETTE(Okabe-Ito 系を両テーマで読める明度に調整した 6 色のカテゴリ色)を足した。color: c.color(i) を系列のストロークに渡すだけで、テキストは currentColor のまま、データの印だけが色づく。check.ts はパレット外の literal 色だけを警告する。

色がないときの系列区別は太さ・破線・不透明度・線端の直接ラベルで行う——規約の「凡例より直接ラベル」「色の名前で印を呼ばない」というルールに、colorless では自動的に従う形だ。colorful 側でも色以外の区別(破線・太さ)は残してあり、色が使えない状況でも読める。

図1: 分布 → ECDF #

問いは「リリース前後でレイテンシはどう散らばるか」。開発者向けの第一選択は ECDF——ビン幅に依存せず、任意のパーセンタイルが直接読める。

v2.3 で p99 レイテンシが 19% 改善(仮想データ) us-east-1 相当の仮想計測、2026-10-01〜10-14、n = 600 / version、生値 出典: 仮想データ (seed 20261101) / n = 600×2 / 集計: なし(生値の ECDF)/ 生成: tools/svg-gen/examples/fig-chart-ecdf.ts 0.0 0.2 0.4 0.6 0.8 1.0 0 100 200 300 400 500 600 700 800 900 レイテンシ (ms) 累積割合 p50 p90 p99 v2.2 v2.3

タイトルの「19%」は手書きではなく、ジェネレータが実際のサンプルの p99 から計算して埋めている。結論タイトルが図とずれる余地がない。系列は v2.2 をグレー(規約の color.baseline)、v2.3 をパレットの青(color.highlight 的な 1 色だけの彩色)にした。p50/p90/p99 の薄いガイド線で読み取りを補助する。

なお 600 点 × 2 系列の全頂点を描くと SVG が 90KB になったので、ecdfPoints に間引きを入れて 150 頂点程度に落とした(統計量は同じで描画だけ疎。27KB になった)。

図2: 時系列 → 折れ線 + イベント線 #

問いは「デプロイを挟んでレイテンシはどう変わったか」。日次集計の p50 と p90 を 2 本の線で、10/08 のデプロイを縦線で注記する。

10/08 デプロイ後に p90 が約 29% 低下(仮想データ) JST、1 時間平均の日次集計、2026-10-01〜10-14、仮想データ 出典: 仮想データ (seed 20261030) / 集計: 日次 / イベント: 10/08 v2.3 デプロイ / 生成: tools/svg-gen/examples/fig-chart-series.ts 0 50 100 150 200 250 300 10/2 10/4 10/6 10/8 10/10 10/12 10/14 日付 (JST) レイテンシ (ms) 10/08 v2.3 デプロイ p50 p90

規約の「デプロイ・設定変更は縦線と短いラベルで注記」「タイムゾーン明記」「集計単位を書く」がそのまま実装項目になった。系列区別は colorful オプション(p50 は青、p90 は朱色)で、破線と太さをフォールバックとして併用している。右端の直接ラベルで凡例箱を引かずに済ませている。

図3: 関係 → 散布図(log 軸) #

問いは「ペイロードサイズとレイテンシはどう関係するか」。3 桁にまたがるペイロードには log 軸を選び、規約どおり軸タイトルに (log) を書いた。

ペイロード 1 桁ごとにレイテンシ +約 43 ms(仮想データ) n = 220 リクエスト、2026-10-14 の 1 時間、生値、仮想データ 出典: 仮想データ (seed 20261031) / n = 220 / 集計: なし(生値)/ 生成: tools/svg-gen/examples/fig-chart-scatter.ts 0 50 100 150 200 250 300 350 400 1 2 5 10 20 50 100 200 500 1000 ペイロード (KiB, log) レイテンシ (ms) 単回帰(説明用)

回帰線は実測の系列と同じ記法にしないため、破線 + パレットの青 + 「単回帰(説明用)」のラベルで「フィットしたモデル」だと分かるようにした。右上の外れ値の束はそのまま残してある——黙って除外すると結論が変わり得るので(除外するなら基準と件数の注記が必須)。

図4: 比較 → 箱ひげ + 生データ点 #

問いは「4 つの実装でベンチマーク結果はどう違うか」。分布の形ごと比べる箱ひげ図を選び、ジッターで散らした生データ点を重ねた(規約は n < 30 で点の重ねを MUST にしているが、n=160 でも間引いた点を重ねると形が読める)。

"cached" は箱では一様だが、実は二峰(仮想データ) ベンチマーク試行 n = 160 / impl、中央値最小は "cached"、仮想データ 出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / n = 160×4 / ひげ: 1.5×IQR / 生成: tools/svg-gen/examples/fig-chart-box.ts 40 60 80 100 120 140 160 180 200 220 240 260 naive simd cached async-io 試行時間 (ms)

ここで罠がある。cached の箱は「ちょっと幅の広い一様な分布」に見えるが、実はこのデータは二峰になっている(速い経路と遅い経路が混ざっている)。規約の制約欄にある「箱ひげは多峰性を隠す」を、わざと再現した。点の方にはうっすら谷が見えるが、箱だけを読むと見逃す。

図5: 分布(同じデータ、別の図)→ ヒストグラム #

図4 と同じ cached のデータ(出典も同じ data.ts)を、ビン幅 10ms のヒストグラムにすると:

"cached" の試行時間は二峰(箱ひげと同じデータ、仮想) ベンチマーク試行 n = 160、ビン幅 10 ms、仮想データ 出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / n = 160 / ビン幅 10 ms / 生成: tools/svg-gen/examples/fig-chart-hist.ts 0 10 20 30 40 50 60 80 100 120 140 160 180 200 試行時間 (ms) 件数

箱ひげが隠した二つの峰がはっきり出る。「同じデータでも図の選択で言えることが変わる」——まさにガイドラインのチャート選択フローが存在する理由で、今回一番気持ちのよい再現だった。ビン幅は規約の MUST どおりサブタイトルに書いた。

図6: 周期 → ヒートマップ(曜日 × 時刻) #

問いは「トラフィックに日次・週次のパターンはあるか」。168 点の時系列を折れ線にするとスパゲッティになるので、曜日 × 時刻のヒートマップにした。色は 1 色相の濃淡(規約の color.sequential)で、currentColor の不透明度で実装した——テーマに追従する単色スケールになる。

Tue 14 時台のスパイクと週末の谷(仮想データ) req/s の 1 時間平均、2026-10-W42 の 1 週間、仮想データ 出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / 集計: 1 時間平均 / 生成: tools/svg-gen/examples/fig-chart-heat.ts Mon Tue Wed Thu Fri Sat Sun 0時 6時 12時 18時 24時 時刻 (JST) 1 204 req/s

火曜 14〜16 時台のインシデント(濃い 3 セル)、昼どきの谷、週末の薄さ、日曜深夜のバッチが読み取れる。凡例は min/max のランプをプロットの外に置いた(最初はラベルがセルに重なり、check.ts に FAIL された)。

作ってみて分かったこと #

  • lint の機械的半分にも新しい失敗があった。check.ts は「テキストが中に収まるべき形状からはみ出す」を検査するのだが、散布図の小さな点(r=1.8 の circle)を「ラベルの容器」と誤認し、回帰線のラベルが点からはみ出ていると FAIL した。「テキストを収めるはずの形状として小さすぎるもの(min(w,h) < 12)は容器に数えない」という修正を入れた。図の種類が増えると lint の仮定もずれる。
  • 直接ラベルは「端」ではなく「離れている場所」に置く。ECDF は 2 系列とも右端が累積割合 1.0 に収まるので、端のラベルは重なる。p80 付近のように曲線が離れている位置を選んで置いた。
  • 推定した線は実測と同じ記法にしない。回帰線を実線で引くと「計測された系列」に見える。破線・色・ラベルの三重で「モデル」を区別した。誤差棒や信頼区間も同じ問題を抱えそう。
  • 箱ひげは本当に多峰性を隠す。規約どおりに作った二峰データで自分が騙された(箱は普通に見える)。「箱ひげで比較 → 怪しい群はヒストグラムか ECDF で確認」が実務の動作になる。
  • **ヒートマップの中ではセルが全部「容器」**。凡例ラベルをランプの下に書くと最上段のセルに吸い込まれて FAIL になった。凡例や注記はプロットの外にまとめて置く。
  • 必須引数化は効く。title/subtitle/footnote はコンストラクタで必須なので、うっかり書き忘れた図が生成される経路がない。
  • 「仮想データ」の明記は毎回書く。条件が揃った図は架空の値でも本物っぽく見えるので、タイトル・サブタイトル・脚注のどれかに必ず入れることにした。
  • 色なし系列は 2〜3 本が限界。太さ・破線・透明度の組み合わせで識別できるのは実質 2〜3 系列で、規約の「折れ線 5 本まで」より手前で限界が来る。colorful オプションはこの限界への回答だが、パレットは「ライト・ダーク両方で読める」制約で選びが絞られる(ダーク地に黒系、ライト地に黄色系は使えない)。それでも足りないならスモールマルチプルに逃がすのが正解に見える(未実装)。
  • 乱数ストリームは 1 本だけ作る。gauss(rng(seed)) と別途 rng(seed) を立てると同じ乱数列を 2 つの目的で使うことになり、無関係なはずの量に相関が出る。最初うっかりそうしていた。

chart-gen への示唆 #

ガイドライン(Claude 版)の付録は、svg-gen を「概念図キット」と「データ図キット」に分ける案を出していた。chart.ts を別ファイルにしてみると、切れ目としては自然だと分かった——概念図側は「同じ座標を二度書かない」ためのアンカー計算が中心で、データ図側は「値から長さ・位置を計算する」ためのスケールが中心で、依存方向も chart.ts → svg.ts の一方向だ。

残っている大きい穴は、誤差棒(推定値の比較では必須級)、スモールマルチプル、バイオリン図あたり。箱ひげ・ヒストグラム・ヒートマップは今回入った。それと「図にするか」「どの抽象レベルか」の判断はツールでは強制できないので、write-slops かガイドライン文書の側に置く、という付録の結論は妥当だった。

余談: issue artifacts は「issue を読む」だけでは見えない #

今回の作業の起点は「issue #113 に添付された HTML artifacts を見て」だったのだが、最初の依頼は「issue を読んで」と言う形で、添付物は見つけられなかった。issue の本文・コメントには添付への言及が一切なく、gh issue view はもちろん REST API の body/comments にも artifact の記述が出てこない。タイムラインや編集履歴にも痕跡はない。

見えたきっかけは、ブラウザで見えるはずの URL …/issues/113/artifacts/3 を直接教えてもらったこと。そこから gh api repos/podhmo/html-sandbox/issues/113/artifacts という専用エンドポイントの存在に気づいた。一覧・個別取得(.artifact.body に HTML 全文)ともにここだけで取れる。

「artifacts を見て」と言えば辿り着けるか、はたぶん辿り着ける——エンドポイント名がそのまま artifacts なので、gh api に試せば当たる。問題はそもそも存在を知らないことで、「issue を読んで」ではコメントを眺めて終わる。添付物を見てほしい場合は、URL か「artifacts」という単語を明示するのが確実。

追記: プロット領域のはみ出しは構造で防ぐ #

公開後に気づいたが、ヒストグラムの山(ビン最大 40)と散布図の外れ値(最大 377ms)が、ハードコードした軸上限(30 / 320)を超えてプロット領域を突き抜けていた。viewBox はキャンバス全体から計算されるので、はみ出た要素も「viewBox の内側」——check.ts は拾えない。

対策は 2 段。

  • 作図時点で止める: Plot の各マーク生成メソッドが、点がドメイン内にあるかを emit 時に検査し、外なら例外で生成自体を止める(inside())。これで導入直後に ECDF のドメインも間違っていたこと(x 範囲が 21.5〜840.8 に対して 40〜800 固定)と、箱ひげのジッターが右端をはみ出すことも炙り出せた。ヒストグラムの ydom は最大ビン数から計算するようにした。
  • check.ts で検証できる形状にする: マーク呼び出しを p.data(() => { ... }) で囲むと、生成要素が <g data-plot="x0 y0 x1 y1"> という概念的な親領域にまとまる。check.ts はこのグループの中の要素をプロット矩形に対して検査するので、viewBox に収まっているがプロットからはみ出ているものも FAIL になる。軸ラベルや凡例のような「外にいるのが正しい」要素はグループの外に置くので誤検知しない。

「ドメインはデータから決めるか、収まることを assert で表明する」という前の結論を、キット側の構造にまで引き上げた形。ジッターのような描画上のずれ(データではなく見た目のオフセット)は assert ではなくクランプで対応した。

検証 #

make -C tools/svg-gen で全 11 図を生成し check.ts を通した(0 failure、パレット色は警告対象外)。PNG は rsvg-convert で rasterize し、ライト・ダーク両方の見え方を確認した(ダーク側は currentColor を明色に置き換えたコピー + 暗色背景、および Go 版ブログ make -C go watch の /slops/chart-gen 実ページ)。メンバーの raw ルート(/slops/chart-gen/chart.ts など)と prev/next チェーン(slops-nav)も確認済み。

ジェネレータと仮想データはバンドルのメンバーにしてある: fig-chart-ecdf.ts, fig-chart-series.ts, fig-chart-scatter.ts, fig-chart-box.ts, fig-chart-hist.ts, fig-chart-heat.ts, chart.ts, data.ts。

01-fig-chart-ecdf.ts #

// fig-chart-ecdf.ts -- ECDF of request latency for two release versions.
// The "distribution" branch of the chart-selection flow: for a
// developer audience the first choice is ECDF (any percentile is
// readable directly, no bin width to declare). Data is virtual —
// lognormal samples from a seeded PRNG, regenerated identically
// every run.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot, ecdfPoints, gauss, quantile, rng } from "../chart.ts";

const c = new Canvas();
const g = gauss(rng(20261101));
const sample = (mu: number, sigma: number, n: number) =>
  Array.from({ length: n }, () => Math.exp(mu + sigma * g())).sort((a, b) => a - b);

// virtual request latency (ms), before and after a deploy
const v22 = sample(Math.log(140), 0.55, 600);
const v23 = sample(Math.log(105), 0.5, 600);

const gain = Math.round((1 - quantile(v23, 0.99) / quantile(v22, 0.99)) * 100);

const p = new Plot(
  c,
  {
    title: `v2.3 で p99 レイテンシが ${gain}% 改善(仮想データ)`,
    subtitle: "us-east-1 相当の仮想計測、2026-10-01〜10-14、n = 600 / version、生値",
    footnote: "出典: 仮想データ (seed 20261101) / n = 600×2 / 集計: なし(生値の ECDF)/ 生成: tools/svg-gen/examples/fig-chart-ecdf.ts",
  },
  {
    w: 420,
    h: 190,
    xdom: [0, 900],
    ydom: [0, 1],
    xtitle: "レイテンシ (ms)",
    ytitle: "累積割合",
    yfmt: (v) => v.toFixed(1),
    grid: true,
  },
);
p.frame();
// faint guides at p50 / p90 / p99 so the improvement is readable off axes.
p.data(() => {
  for (const q of [0.5, 0.9, 0.99]) {
    p.hline(q, { label: `p${q * 100}`, opacity: 0.25 });
  }
  // stride-thinned to ~150 vertices per curve for inline embedding;
  // the ECDF statistic itself is unchanged.
  // v2.2 is the grey baseline; v2.3 gets the one palette accent
  // (the guideline's "highlight = one colour, rest grey").
  p.step(ecdfPoints(p, v22, 150), { opacity: 0.65 });
  p.step(ecdfPoints(p, v23, 150), { width: 2.5, color: c.color(0) });
});
// direct labels where the curves are far apart (near their p80).
const at = (s: number[], q: number) => p.xs.map(quantile(s, q));
const y80 = p.ys.map(0.8);
c.text(at(v22, 0.8) + 6, y80, "v2.2", { baseline: "central", size: 11, opacity: 0.65 });
c.text(at(v23, 0.8) + 6, y80 - 14, "v2.3", { baseline: "central", size: 11 });

assert.ok(gain > 0, "v2.3 improves p99 over v2.2");

await writeFile(
  new URL("../build/fig-chart-ecdf.svg", import.meta.url),
  c.toString({ label: `ECDF of request latency: p99 improves ${gain}% in v2.3 (virtual data)` }),
);

02-fig-chart-series.ts #

// fig-chart-series.ts -- daily latency percentiles around a deploy.
// The "time series" branch of the chart-selection flow: lines for the
// trend, a vertical event line for the deploy. Data is virtual —
// two weeks of daily-aggregated p50/p90 from a seeded PRNG.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot, gauss, rng } from "../chart.ts";

const c = new Canvas();
const g = gauss(rng(20261030));

// virtual daily aggregates: a latency drop after the 10/08 deploy,
// with day-of-week wobble and noise.
const days = Array.from({ length: 14 }, (_, i) => i + 1); // Oct 1..14
const base = (d: number) => (d < 8 ? 150 : 105);
const weekly = (d: number) => (d % 7 === 6 || d % 7 === 0 ? 12 : 0); // weekend bump
const p50 = days.map((d) => base(d) + weekly(d) + 5 * g());
const p90 = days.map((d, i) => p50[i] * 1.7 + weekly(d) + 12 * g());

const mean = (a: number[]) => a.reduce((s, v) => s + v, 0) / a.length;
const drop = Math.round((1 - mean(p90.slice(8)) / mean(p90.slice(0, 8))) * 100);

const p = new Plot(
  c,
  {
    title: `10/08 デプロイ後に p90 が約 ${drop}% 低下(仮想データ)`,
    subtitle: "JST、1 時間平均の日次集計、2026-10-01〜10-14、仮想データ",
    footnote: "出典: 仮想データ (seed 20261030) / 集計: 日次 / イベント: 10/08 v2.3 デプロイ / 生成: tools/svg-gen/examples/fig-chart-series.ts",
  },
  {
    w: 420,
    h: 170,
    xdom: [1, 14],
    ydom: [0, 320],
    xtitle: "日付 (JST)",
    ytitle: "レイテンシ (ms)",
    xfmt: (v) => `10/${v}`,
    grid: true,
  },
);
p.frame();
p.data(() => {
  p.vline(8, { label: "10/08 v2.3 デプロイ" });
  // colorful option: hue does the series distinction, width/dash stays
  // as a grayscale fallback so the figure still reads when colors
  // are unavailable (print, copy).
  p.series(days.map((d, i) => [p.xs.map(d), p.ys.map(p90[i])]), { dash: "5 3", color: c.color(3) });
  p.series(days.map((d, i) => [p.xs.map(d), p.ys.map(p50[i])]), { width: 2.5, color: c.color(0) });
});
// direct labels at the right ends (the two series end far apart).
c.text(p.x1 + 6, p.ys.map(p50[13]), "p50", { baseline: "central", size: 10 });
c.text(p.x1 + 6, p.ys.map(p90[13]), "p90", { baseline: "central", size: 10, opacity: 0.65 });

assert.ok(drop > 10, "p90 clearly drops after the deploy");

await writeFile(
  new URL("../build/fig-chart-series.svg", import.meta.url),
  c.toString({ label: `daily p50/p90 latency: p90 drops about ${drop}% after the 10/08 deploy (virtual data)` }),
);

03-fig-chart-scatter.ts #

// fig-chart-scatter.ts -- payload size vs latency, log x axis.
// The "relationship" branch of the chart-selection flow: a scatter of
// raw request pairs. Data is virtual — 220 requests from a seeded
// PRNG, with a handful of timeout-ish outliers.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot, gauss, rng } from "../chart.ts";

const c = new Canvas();
const rand = rng(20261031);
const g = gauss(rand);

// virtual pairs: payload (KiB) spans 3 decades on a log axis;
// latency grows ~linearly in log10(payload) plus noise and outliers.
const pairs: [number, number][] = [];
for (let i = 0; i < 220; i++) {
  const lx = 3 * rand(); // log10(KiB), 1 .. 1M KiB? no: 0..3 -> 1KiB..1MiB
  const payload = Math.pow(10, lx);
  const outlier = rand() < 0.04 ? 160 + 60 * rand() : 0;
  const latency = 35 + 42 * lx + 22 * g() + outlier;
  pairs.push([payload, Math.max(latency, 8)]);
}

// least squares on log10(payload) -> the "+N ms per decade" headline.
const xs = pairs.map(([v]) => Math.log10(v));
const ys = pairs.map(([, v]) => v);
const mx = xs.reduce((s, v) => s + v) / xs.length;
const my = ys.reduce((s, v) => s + v) / ys.length;
const slope =
  xs.reduce((s, v, i) => s + (v - mx) * (ys[i] - my), 0) /
  xs.reduce((s, v) => s + (v - mx) * (v - mx), 0);
const perDecade = Math.round(slope);

const p = new Plot(
  c,
  {
    title: `ペイロード 1 桁ごとにレイテンシ +約 ${perDecade} ms(仮想データ)`,
    subtitle: "n = 220 リクエスト、2026-10-14 の 1 時間、生値、仮想データ",
    footnote: "出典: 仮想データ (seed 20261031) / n = 220 / 集計: なし(生値)/ 生成: tools/svg-gen/examples/fig-chart-scatter.ts",
  },
  {
    w: 420,
    h: 190,
    xdom: [1, 1000],
    ydom: [0, 400],
    xlog: true,
    xtitle: "ペイロード (KiB, log)",
    ytitle: "レイテンシ (ms)",
    grid: true,
  },
);
p.frame();
// regression guide, drawn dashed so it reads as "a fitted model",
// not as another measured series.
const lx = (v: number) => my + slope * (v - mx);
p.data(() => {
  p.dots(pairs.map(([x, y]) => [p.xs.map(x), p.ys.map(y)]), { r: 1.8, opacity: 0.45 });
  p.series(
    [
      [p.xs.map(1), p.ys.map(lx(0))],
      [p.xs.map(1000), p.ys.map(lx(3))],
    ],
    { dash: "2 3", opacity: 0.8, color: c.color(0) },
  );
});
c.text(p.xs.map(300), p.ys.map(lx(Math.log10(300))) - 8, "単回帰(説明用)", {
  anchor: "middle",
  size: 10,
  opacity: 0.7,
});

const ymax = Math.max(...ys);
assert.ok(ymax <= 400, "outliers stay inside the y domain");
assert.ok(perDecade > 20 && perDecade < 60, "slope lands in the designed range");

await writeFile(
  new URL("../build/fig-chart-scatter.svg", import.meta.url),
  c.toString({ label: `scatter of payload size vs latency: about +${perDecade} ms per decade of payload (virtual data)` }),
);

04-fig-chart-box.ts #

// fig-chart-box.ts -- box-and-whisker for four benchmark variants,
// raw points jittered on top. The "cached" group is secretly bimodal
// (data.ts): the box reports one compact distribution, which is the
// guideline's own warning — a box plot hides multimodality — made
// visible here by the jittered points.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot, quantile, rng } from "../chart.ts";
import { bench } from "./data.ts";

const c = new Canvas();
const jitter = rng(20261103);

const medians = bench.map((b) => quantile([...b.values].sort((a, b2) => a - b2), 0.5));
const best = bench[medians.indexOf(Math.min(...medians))].label;

const p = new Plot(
  c,
  {
    title: `"cached" は箱では一様だが、実は二峰(仮想データ)`,
    subtitle: `ベンチマーク試行 n = 160 / impl、中央値最小は "${best}"、仮想データ`,
    footnote:
      "出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / n = 160×4 / ひげ: 1.5×IQR / 生成: tools/svg-gen/examples/fig-chart-box.ts",
  },
  {
    w: 420,
    h: 190,
    xdom: [0, bench.length],
    ydom: [40, 260],
    ytitle: "試行時間 (ms)",
    grid: true,
  },
);
p.frame({
  xticks: bench.map((b, i) => [i + 0.5, b.label] as [number, string]),
});
// faint jittered points (thinned): the box alone hides shape, so the
// points carry the multimodality the boxes cannot show.
p.data(() => p.boxplot(bench, { overlay: 0.25, rand: jitter, color: c.color(0) }));

assert.ok(bench.length === 4, "four benchmark groups drawn");

await writeFile(
  new URL("../build/fig-chart-box.svg", import.meta.url),
  c.toString({ label: "box plot of four benchmark variants; the cached group is secretly bimodal (virtual data)" }),
);

05-fig-chart-hist.ts #

// fig-chart-hist.ts -- histogram of the same "cached" group the box
// plot flattened. Same virtual dataset (data.ts), different figure:
// the two modes the box hid are obvious here. The bin width is
// declared in the subtitle, as the guideline requires.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot, bins } from "../chart.ts";
import { bench } from "./data.ts";

const c = new Canvas();

const cached = bench.find((b) => b.label === "cached")!;
const binW = 10;
const bs = bins(cached.values, binW);
// two modes: a dip below 45% of the peak somewhere between the modes
const peak = Math.max(...bs.map((b) => b.n));
const mid = bs.findIndex((b) => b.x0 >= 110);
const dip = Math.min(...bs.slice(4, mid + 1).map((b) => b.n));

const p = new Plot(
  c,
  {
    title: `"cached" の試行時間は二峰(箱ひげと同じデータ、仮想)`,
    subtitle: `ベンチマーク試行 n = ${cached.values.length}、ビン幅 ${binW} ms、仮想データ`,
    footnote:
      "出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / n = 160 / ビン幅 10 ms / 生成: tools/svg-gen/examples/fig-chart-hist.ts",
  },
  {
    w: 420,
    h: 170,
    xdom: [60, 200],
    // ~10% headroom above the tallest bin, rounded up to a tick step
    ydom: [0, Math.ceil(peak * 1.1 / 10) * 10],
    xtitle: "試行時間 (ms)",
    ytitle: "件数",
    grid: true,
  },
);
p.frame();
p.data(() => p.histogram(bs, { color: c.color(0) }));

assert.ok(dip < peak * 0.5, "a visible dip separates the two modes");
assert.ok(peak <= 45, "tallest bin stays inside the y domain");

await writeFile(
  new URL("../build/fig-chart-hist.svg", import.meta.url),
  c.toString({ label: "histogram of cached trials showing two modes (same virtual data as the box plot)" }),
);

06-fig-chart-heat.ts #

// fig-chart-heat.ts -- traffic heatmap, day x hour. The "time
// series / periodicity" branch: a heatmap shows daily and weekly
// patterns that 168 points of spaghetti lines would not.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "../svg.ts";
import { Plot } from "../chart.ts";
import { traffic, trafficDays } from "./data.ts";

const c = new Canvas();

// find the peak cell for the conclusion title
let peak = { d: 0, h: 0, v: 0 };
traffic.forEach((row, d) =>
  row.forEach((v, h) => {
    if (v > peak.v) peak = { d, h, v };
  }),
);

const p = new Plot(
  c,
  {
    title: `${trafficDays[peak.d]} ${peak.h} 時台のスパイクと週末の谷(仮想データ)`,
    subtitle: "req/s の 1 時間平均、2026-10-W42 の 1 週間、仮想データ",
    footnote:
      "出典: 仮想データ (tools/svg-gen/examples/data.ts, seed 20261102) / 集計: 1 時間平均 / 生成: tools/svg-gen/examples/fig-chart-heat.ts",
  },
  {
    w: 440,
    h: 150,
    xdom: [0, 24],
    ydom: [0, 7],
    xtitle: "時刻 (JST)",
  },
);
p.frame({
  xticks: [0, 6, 12, 18, 24].map((h) => [h, `${h}時`] as [number, string]),
  yticks: trafficDays.map((d, i) => [traffic.length - 0.5 - i, d] as [number, string]),
});
let mm!: { min: number; max: number };
p.data(() => {
  mm = p.heatmap(traffic);
});
p.heatLegend(mm, { x: p.x1 - 80, y: p.y0 - 24, fmt: (v) => String(Math.round(v)), label: "req/s" });

assert.ok(peak.d === 1, "the incident peak is on Tuesday");

await writeFile(
  new URL("../build/fig-chart-heat.svg", import.meta.url),
  c.toString({ label: `traffic heatmap: peak on ${trafficDays[peak.d]} around ${peak.h}:00, weekends quiet (virtual data)` }),
);

chart.ts #

// chart.ts -- data-figure helpers for svg-gen: scales, axes, and series
// for statistical figures (the L1 side of the figure guideline in
// docs/sketch/ja/figure-guidelines.md). svg.ts still owns drawing and
// the viewBox; this file owns data -> pixel mapping and the chart
// frame, and makes the "required metadata" required in the type:
// every Plot needs {title, subtitle, footnote} up front.

import { Canvas, textWidth } from "./svg.ts";
import type { Point, StrokeOptions } from "./svg.ts";

// Deterministic PRNG (mulberry32) so a figure's virtual data is
// reproducible from its seed alone.
export function rng(seed: number): () => number {
  let a = seed >>> 0;
  return () => {
    a |= 0;
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// Box-Muller on top of rng().
export function gauss(rand: () => number): () => number {
  return () => {
    const u = Math.max(rand(), 1e-12);
    const v = rand();
    return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
  };
}

export function quantile(sorted: number[], q: number): number {
  const i = (sorted.length - 1) * q;
  const lo = Math.floor(i);
  const hi = Math.ceil(i);
  return sorted[lo] + (sorted[hi] - sorted[lo]) * (i - lo);
}

// 1/2/5-style nice ticks covering [lo, hi], about `count` of them.
export function ticks(lo: number, hi: number, count = 5): number[] {
  const raw = (hi - lo) / count;
  const p = Math.pow(10, Math.floor(Math.log10(raw)));
  const f = raw / p;
  const step = (f >= 5 ? 5 : f >= 2 ? 2 : 1) * p;
  const out: number[] = [];
  for (let v = Math.ceil(lo / step - 1e-9) * step; v <= hi + step * 1e-6; v += step) {
    out.push(+v.toPrecision(12));
  }
  return out;
}

// A data->pixel mapping. `log` works on the data value (v > 0 only).
export class Scale {
  lo: number;
  hi: number;
  a: number;
  b: number;
  log: boolean;

  constructor(lo: number, hi: number, a: number, b: number, log = false) {
    this.lo = lo;
    this.hi = hi;
    this.a = a;
    this.b = b;
    this.log = log;
  }

  private spread(): [number, number] {
    return this.log ? [Math.log10(this.lo), Math.log10(this.hi)] : [this.lo, this.hi];
  }

  map(v: number): number {
    const [l, h] = this.spread();
    const x = this.log ? Math.log10(v) : v;
    return this.a + ((x - l) / (h - l)) * (this.b - this.a);
  }

  ticks(count = 5): number[] {
    if (!this.log) return ticks(this.lo, this.hi, count);
    // log axis: mark 1/2/5 of each decade inside the domain.
    const [l, h] = this.spread();
    const out: number[] = [];
    for (let d = Math.floor(l); d <= Math.ceil(h); d++) {
      for (const m of [1, 2, 5]) {
        const v = m * Math.pow(10, d);
        if (v >= this.lo && v <= this.hi) out.push(v);
      }
    }
    return out;
  }
}

export interface ChartMeta {
  title: string; // the conclusion, e.g. "p99 dropped 38% in v2.3"
  subtitle: string; // conditions: environment, period, n, aggregation
  footnote: string; // provenance: source / period / n / aggregation / generator
}

export interface PlotOpts {
  x?: number;
  y?: number;
  w?: number;
  h?: number;
  xdom: [number, number];
  ydom: [number, number];
  xlog?: boolean;
  ylog?: boolean;
  xtitle?: string; // include the unit, e.g. "latency (ms)"
  ytitle?: string;
  xfmt?: (v: number) => string;
  yfmt?: (v: number) => string;
  grid?: boolean; // faint horizontal lines at the y ticks
}

const fmtNum = (v: number): string => String(v);

// A tick is either a position formatted by xfmt/yfmt, or
// [position, label] for categorical axes.
export type Tick = number | [number, string];

export class Plot {
  readonly x0: number;
  readonly y0: number;
  readonly x1: number;
  readonly y1: number;
  readonly xs: Scale;
  readonly ys: Scale;
  readonly meta: ChartMeta;
  private xfmt: (v: number) => string;
  private yfmt: (v: number) => string;
  private xtitle?: string;
  private ytitle?: string;
  private grid: boolean;
  private framed = false;
  private c: Canvas;
  // While data() runs, mark elements collect here and are emitted as
  // one <g data-plot="x0 y0 x1 y1"> group — the conceptual parent
  // region check.ts can verify against.
  private buf: string[] | null = null;

  private put(el: string, covered: [number, number][] = []): void {
    if (this.buf) this.buf.push(el);
    else this.c.raw(el, covered);
  }

  // Marks must stay inside the plot domain: a value outside it is a
  // wrong domain choice, not a detail to clip silently.
  private inside(pts: [number, number][]): [number, number][] {
    for (const [x, y] of pts) {
      if (x < this.x0 - 0.01 || x > this.x1 + 0.01 || y < this.y0 - 0.01 || y > this.y1 + 0.01) {
        throw new Error(`point (${x.toFixed(1)}, ${y.toFixed(1)}) outside the plot domain`);
      }
    }
    return pts;
  }

  // Run mark-emitting calls; their elements go into a
  // <g data-plot="x0 y0 x1 y1"> group so check.ts can verify them
  // against the plot area instead of only the viewBox.
  data(fn: (p: Plot) => void): this {
    const buf: string[] = [];
    const prev = this.buf;
    this.buf = buf;
    try {
      fn(this);
    } finally {
      this.buf = prev;
    }
    if (buf.length) {
      this.c.raw(
        `<g data-plot="${this.x0} ${this.y0} ${this.x1} ${this.y1}">\n${buf.join("\n")}\n</g>`,
        [[this.x0, this.y0], [this.x1, this.y1]],
      );
    }
    return this;
  }

  private sattrs(o: { dash?: string; opacity?: number; width?: number; color?: string }): string {
    const w = ` stroke-width="${o.width ?? 1.5}"`;
    const d = o.dash ? ` stroke-dasharray="${o.dash}"` : "";
    const p = o.opacity != null ? ` opacity="${o.opacity}"` : "";
    return ` stroke="${o.color ?? "currentColor"}"${w}${d}${p}`;
  }

  constructor(c: Canvas, meta: ChartMeta, o: PlotOpts) {
    this.c = c;
    this.meta = meta;
    this.x0 = o.x ?? 0;
    this.y0 = o.y ?? 0;
    const w = o.w ?? 420;
    const h = o.h ?? 200;
    this.x1 = this.x0 + w;
    this.y1 = this.y0 + h;
    this.xs = new Scale(o.xdom[0], o.xdom[1], this.x0, this.x1, o.xlog ?? false);
    this.ys = new Scale(o.ydom[0], o.ydom[1], this.y1, this.y0, o.ylog ?? false);
    this.xfmt = o.xfmt ?? fmtNum;
    this.yfmt = o.yfmt ?? fmtNum;
    this.xtitle = o.xtitle;
    this.ytitle = o.ytitle;
    this.grid = o.grid ?? false;
    // The frame texts land at construction so a caller cannot forget them.
    c.text(this.x0, this.y0 - 40, meta.title, { size: 15 });
    c.text(this.x0, this.y0 - 22, meta.subtitle, { size: 11, opacity: 0.65 });
    c.text(this.x0, this.y1 + 42, meta.footnote, { size: 10, opacity: 0.55 });
  }

  // Axis lines, tick labels, axis titles. Called once per plot.
  // Pass xticks/yticks to override the generated ones — e.g. for
  // categorical axes ([pos, label] entries).
  frame(o: { xticks?: Tick[]; yticks?: Tick[] } = {}): this {
    if (this.framed) return this;
    this.framed = true;
    const c = this.c;
    c.line([this.x0, this.y0], [this.x0, this.y1], { opacity: 0.45, width: 1 });
    c.line([this.x0, this.y1], [this.x1, this.y1], { opacity: 0.45, width: 1 });
    const yts: [number, string][] = (o.yticks ?? this.ys.ticks()).map((t) =>
      Array.isArray(t) ? t : [t, this.yfmt(t)],
    );
    for (const [v, label] of yts) {
      const py = this.ys.map(v);
      c.line([this.x0 - 3, py], [this.x0, py], { opacity: 0.5, width: 1 });
      c.text(this.x0 - 6, py, label, { anchor: "end", baseline: "central", size: 10, opacity: 0.7 });
      if (this.grid) c.line([this.x0, py], [this.x1, py], { opacity: 0.1, width: 1 });
    }
    const xts: [number, string][] = (o.xticks ?? this.xs.ticks()).map((t) =>
      Array.isArray(t) ? t : [t, this.xfmt(t)],
    );
    for (const [v, label] of xts) {
      const px = this.xs.map(v);
      c.line([px, this.y1], [px, this.y1 + 3], { opacity: 0.5, width: 1 });
      c.text(px, this.y1 + 16, label, { anchor: "middle", size: 10, opacity: 0.7 });
    }
    if (this.xtitle) {
      c.text((this.x0 + this.x1) / 2, this.y1 + 30, this.xtitle, { anchor: "middle", size: 10, opacity: 0.7 });
    }
    if (this.ytitle) {
      // horizontal, above the axis top-left: readable without rotation.
      c.text(this.x0, this.y0 - 8, this.ytitle, { size: 10, opacity: 0.7 });
    }
    return this;
  }

  // A connected series. `label` draws the series name at its right end
  // (direct labelling, not a legend box).
  series(pts: Point[], o: StrokeOptions & { label?: string } = {}): this {
    if (pts.length < 2) return this;
    const { label, ...stroke } = o;
    this.put(
      `<path d="M${this.inside(pts).map(([x, y]) => `${x} ${y}`).join(" L")}" fill="none"${this.sattrs(stroke)}/>`,
      pts,
    );
    if (label) {
      this.c.text(this.x1 + 6, pts[pts.length - 1][1], label, { baseline: "central", size: 10 });
    }
    return this;
  }

  // Step series for ECDF: horizontal then vertical at each point.
  step(pts: Point[], o: StrokeOptions & { label?: string } = {}): this {
    if (pts.length < 2) return this;
    const { label, ...stroke } = o;
    const segs: Point[] = [pts[0]];
    for (let i = 1; i < pts.length; i++) {
      segs.push([pts[i][0], pts[i - 1][1]], pts[i]);
    }
    this.put(
      `<path d="M${this.inside(segs).map(([x, y]) => `${x} ${y}`).join(" L")}" fill="none"${this.sattrs(stroke)}/>`,
      segs,
    );
    if (label) {
      this.c.text(this.x1 + 6, pts[pts.length - 1][1], label, { baseline: "central", size: 10 });
    }
    return this;
  }

  dots(pts: Point[], { r = 1.8, opacity = 0.5, color }: { r?: number; opacity?: number; color?: string } = {}): this {
    const fill = color ?? "currentColor";
    for (const [x, y] of this.inside(pts)) {
      this.put(
        `<circle cx="${x}" cy="${y}" r="${r}" fill="${fill}" fill-opacity="${opacity}" stroke="none"/>`,
        [[x, y]],
      );
    }
    // dots do not extend the viewBox; the frame's domain already does.
    return this;
  }

  // An event marker: vertical line at data x, with a short label above.
  vline(xv: number, { label, dash = "4 3", opacity = 0.6 }: { label?: string; dash?: string; opacity?: number } = {}): this {
    const px = this.xs.map(xv);
    this.put(
      `<line x1="${px}" y1="${this.y0}" x2="${px}" y2="${this.y1}"${this.sattrs({ dash, opacity, width: 1 })}/>`,
      [[px, this.y0], [px, this.y1]],
    );
    this.inside([[px, this.y0]]);
    if (label) {
      this.c.text(px + 4, this.y0 + 10, label, { size: 10, opacity: 0.8 });
    }
    return this;
  }

  // A reference line (SLO, baseline): horizontal line at data y.
  hline(yv: number, { label, dash = "4 3", opacity = 0.6 }: { label?: string; dash?: string; opacity?: number } = {}): this {
    const py = this.ys.map(yv);
    this.put(
      `<line x1="${this.x0}" y1="${py}" x2="${this.x1}" y2="${py}"${this.sattrs({ dash, opacity, width: 1 })}/>`,
      [[this.x0, py], [this.x1, py]],
    );
    this.inside([[this.x0, py]]);
    if (label) {
      this.c.text(this.x1 - 4, py - 4, label, { anchor: "end", size: 10, opacity: 0.8 });
    }
    return this;
  }

  // Box-and-whisker per group, centred at x = i + 0.5 (use xdom
  // [0, groups.length]). Whiskers reach the 1.5*IQR fences clamped
  // to the data range; values beyond are outlier dots. `overlay`
  // jitters raw points behind the boxes — the guideline wants raw
  // points overlaid for small n because the box alone hides shape.
  boxplot(
    groups: { label: string; values: number[] }[],
    { boxW = 0.44, overlay = 0, color, rand }: { boxW?: number; overlay?: number; color?: string; rand?: () => number } = {},
  ): this {
    const c = this.c;
    const stride = overlay > 0 && overlay < 1 ? Math.max(1, Math.round(1 / overlay)) : 1;
    groups.forEach((g, i) => {
      const s = [...g.values].sort((a, b) => a - b);
      const q1 = quantile(s, 0.25);
      const q2 = quantile(s, 0.5);
      const q3 = quantile(s, 0.75);
      const iqr = q3 - q1;
      const lo = Math.max(s[0], q1 - 1.5 * iqr);
      const hi = Math.min(s[s.length - 1], q3 + 1.5 * iqr);
      const cx = this.xs.map(i + 0.5);
      const bw = (this.xs.map(i + 0.5 + boxW) - cx) * 2;
      if (overlay > 0 && rand) {
        for (let j = 0; j < s.length; j += stride) {
          const jx = Math.min(Math.max(cx + (rand() - 0.5) * bw * 1.6, this.x0 + 1.5), this.x1 - 1.5); // jitter stays inside the domain
          this.put(`<circle cx="${jx.toFixed(1)}" cy="${this.ys.map(s[j]).toFixed(1)}" r="1.3" fill="${color ?? "currentColor"}" fill-opacity="0.28" stroke="none"/>`);
        }
      }
      // whiskers + caps
      this.inside([[cx, this.ys.map(lo)], [cx, this.ys.map(hi)]]);
      this.put(`<line x1="${cx}" y1="${this.ys.map(lo)}" x2="${cx}" y2="${this.ys.map(hi)}"${this.sattrs({ width: 1, color, opacity: 0.8 })}/>`);
      this.put(`<line x1="${cx - bw * 0.2}" y1="${this.ys.map(lo)}" x2="${cx + bw * 0.2}" y2="${this.ys.map(lo)}"${this.sattrs({ width: 1, color })}/>`);
      this.put(`<line x1="${cx - bw * 0.2}" y1="${this.ys.map(hi)}" x2="${cx + bw * 0.2}" y2="${this.ys.map(hi)}"${this.sattrs({ width: 1, color })}/>`);
      // outliers beyond the fences
      for (const v of s) {
        if (v < lo || v > hi) {
          this.put(`<circle cx="${cx.toFixed(1)}" cy="${this.ys.map(v).toFixed(1)}" r="1.6" fill="none" stroke="${color ?? "currentColor"}" stroke-width="1" opacity="0.6"/>`);
        }
      }
      // IQR box + median
      this.put(
        `<rect x="${(cx - bw / 2).toFixed(1)}" y="${this.ys.map(q3).toFixed(1)}" width="${bw.toFixed(1)}" height="${(this.ys.map(q1) - this.ys.map(q3)).toFixed(1)}" fill="${color ?? "currentColor"}" fill-opacity="0.18" stroke="${color ?? "currentColor"}" stroke-width="1.5"/>`,
      );
      this.put(`<line x1="${cx - bw / 2}" y1="${this.ys.map(q2)}" x2="${cx + bw / 2}" y2="${this.ys.map(q2)}"${this.sattrs({ width: 2.5, color })}/>`);
    });
    return this;
  }

  // Histogram bars from bins() output; heights are counts.
  histogram(bins: { x0: number; x1: number; n: number }[], { color }: { color?: string } = {}): this {
    for (const b of bins) {
      const x = this.xs.map(b.x0);
      const w = this.xs.map(b.x1) - x;
      const top = this.inside([[this.xs.map(b.x0), this.ys.map(b.n)]])[0][1];
      this.put(
        `<rect x="${x.toFixed(1)}" y="${top.toFixed(1)}" width="${w.toFixed(1)}" height="${(this.y1 - top).toFixed(1)}" fill="${color ?? "currentColor"}" fill-opacity="0.35" stroke="${color ?? "currentColor"}" stroke-width="1"/>`,
      );
    }
    return this;
  }

  // Cells of a rows x cols grid; fill-opacity encodes value against
  // the data max (sequential single-hue scale: currentColor keeps it
  // theme-following). Row 0 draws at the top. Returns {min, max} for
  // the legend.
  heatmap(
    grid: number[][],
    { color }: { color?: string } = {},
  ): { min: number; max: number } {
    const rows = grid.length;
    const cols = grid[0].length;
    const cw = (this.x1 - this.x0) / cols;
    const ch = (this.y1 - this.y0) / rows;
    let min = Infinity;
    let max = -Infinity;
    for (const row of grid) for (const v of row) { min = Math.min(min, v); max = Math.max(max, v); }
    const span = max - min || 1;
    grid.forEach((row, j) => {
      row.forEach((v, i) => {
        const o = 0.06 + 0.9 * ((v - min) / span);
        this.put(
          `<rect x="${(this.x0 + i * cw).toFixed(1)}" y="${(this.y0 + j * ch).toFixed(1)}" width="${(cw - 0.6).toFixed(1)}" height="${(ch - 0.6).toFixed(1)}" fill="${color ?? "currentColor"}" fill-opacity="${o.toFixed(2)}" stroke="none"/>`,
        );
      });
    });
    return { min, max };
  }

  // Legend ramp for heatmap(): N steps of increasing fill-opacity
  // with min/max labels below and an optional caption to the left.
  // Position it above the plot top so labels stay clear of cells.
  heatLegend(
    { min, max }: { min: number; max: number },
    { x, y, w = 70, fmt = fmtNum, label }: { x: number; y: number; w?: number; fmt?: (v: number) => string; label?: string } = {},
  ): this {
    const steps = 6;
    const sw = w / steps;
    for (let i = 0; i < steps; i++) {
      const o = 0.06 + 0.9 * (i / (steps - 1));
      this.c.raw(`<rect x="${(x + i * sw).toFixed(1)}" y="${y}" width="${(sw - 1).toFixed(1)}" height="8" fill="currentColor" fill-opacity="${o.toFixed(2)}" stroke="none"/>`);
    }
    this.c.text(x, y + 16, fmt(min), { size: 9, opacity: 0.6 });
    this.c.text(x + w, y + 16, fmt(max), { anchor: "end", size: 9, opacity: 0.6 });
    if (label) this.c.text(x - 6, y + 4, label, { anchor: "end", baseline: "central", size: 9, opacity: 0.6 });
    return this;
  }
}

// Count samples into width-w bins aligned to w*k boundaries.
export function bins(values: number[], w: number): { x0: number; x1: number; n: number }[] {
  const lo = Math.floor(Math.min(...values) / w) * w;
  const hi = Math.ceil(Math.max(...values) / w) * w;
  const out: { x0: number; x1: number; n: number }[] = [];
  for (let x = lo; x < hi - 1e-9; x += w) out.push({ x0: x, x1: x + w, n: 0 });
  for (const v of values) {
    const i = Math.min(out.length - 1, Math.floor((v - lo) / w));
    out[i].n++;
  }
  return out;
}

// Build an ECDF's pixel points from raw samples on a Plot. `max`
// thins the step vertices for inline embedding — the statistic is
// the same, only fewer of its vertices are drawn.
export function ecdfPoints(p: Plot, samples: number[], max = Infinity): Point[] {
  const s = [...samples].sort((a, b) => a - b);
  const stride = Math.max(1, Math.floor(s.length / max));
  const pts: Point[] = [];
  for (let i = 0; i < s.length; i += stride) {
    pts.push([p.xs.map(s[i]), p.ys.map((i + 1) / s.length)]);
  }
  pts.push([p.xs.map(s[s.length - 1]), p.ys.map(1)]);
  return pts;
}

data.ts #

// data.ts -- the shared virtual datasets for fig-chart-*.ts, so a
// "same data, different figure" comparison (boxplot vs histogram)
// reads from one source. Everything is seeded; values are virtual,
// not measurements.
import { gauss, rng } from "../chart.ts";

const rand = rng(20261102);
const g = gauss(rand);
const nrm = (mu: number, sd: number, n: number): number[] =>
  Array.from({ length: n }, () => mu + sd * g());

// Virtual benchmark trials (ms), n=160 per implementation. "cached"
// is secretly bimodal: a fast path hit vs. a miss path. A box plot
// reports it as one compact distribution; a histogram shows the two
// modes. The choice of figure changes what the data says — which is
// the guideline's own warning, reproduced on purpose.
export const bench: { label: string; values: number[] }[] = [
  { label: "naive", values: nrm(150, 18, 160) },
  { label: "simd", values: nrm(105, 12, 160) },
  {
    label: "cached",
    values: [...nrm(88, 9, 96), ...nrm(168, 14, 64)],
  },
  {
    label: "async-io",
    values: nrm(120, 22, 160).map((v) => (v > 150 ? v + 40 * rand() : v)),
  },
];

// Virtual hourly traffic (req/s), 7 days x 24 hours: a daytime
// plateau, a lunchtime dip, quieter weekends, and an incident
// window on Tuesday 14:00-17:00.
export const traffic: number[][] = (() => {
  const hourly = (h: number) =>
    h < 7 ? 15 : h < 9 ? 40 + (h - 7) * 20 : h < 12 ? 80 : h < 13 ? 55 : h < 18 ? 95 : h < 22 ? 60 : 25;
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
  return days.map((_, d) => {
    const weekend = d >= 5 ? 0.35 : 1;
    return Array.from({ length: 24 }, (_, h) => {
      let v = hourly(h) * weekend + 6 * g();
      if (d === 1 && h >= 14 && h <= 16) v *= 2.2; // Tue incident
      if (d === 6 && h >= 1 && h <= 4) v *= 1.8; // Sunday late-night batch
      return Math.max(v, 1);
    });
  });
})();
export const trafficDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];