plotilla 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -2
  3. package/data/boundaries/canada_provinces.geojson +1 -0
  4. package/data/boundaries/eu_countries.geojson +1 -0
  5. package/data/boundaries/us_states.geojson +1 -0
  6. package/data/boundaries/world_countries.geojson +1 -0
  7. package/package.json +62 -4
  8. package/src/colour/colour_scale.ts +80 -0
  9. package/src/colour/palette.ts +220 -0
  10. package/src/examples/example_figures.ts +320 -0
  11. package/src/fields/axis_fields.ts +32 -0
  12. package/src/fields/colour_fields.ts +40 -0
  13. package/src/fields/column_fields.ts +64 -0
  14. package/src/fields/common_fields.ts +13 -0
  15. package/src/fields/decide_plot_axes.ts +77 -0
  16. package/src/fields/marker_fields.ts +16 -0
  17. package/src/figure/plot_figure.ts +67 -0
  18. package/src/figure/resolve_plot_figure.ts +47 -0
  19. package/src/figure/validate_plot_figure.ts +412 -0
  20. package/src/map/boundary_sets.ts +116 -0
  21. package/src/map/check_map_layers.ts +32 -0
  22. package/src/map/fetch_region_outlines.ts +48 -0
  23. package/src/map/geojson.ts +174 -0
  24. package/src/map/map_layers.ts +108 -0
  25. package/src/model/check_axis_shows_years.ts +58 -0
  26. package/src/model/map_model.ts +238 -0
  27. package/src/model/panel_layout.ts +171 -0
  28. package/src/model/panel_model.ts +85 -0
  29. package/src/model/plot_model.ts +347 -0
  30. package/src/model/statistics.ts +134 -0
  31. package/src/plots/bar_plot.ts +36 -0
  32. package/src/plots/box_plot.ts +26 -0
  33. package/src/plots/density_plot.ts +29 -0
  34. package/src/plots/heatmap_plot.ts +24 -0
  35. package/src/plots/histogram_plot.ts +29 -0
  36. package/src/plots/line_plot.ts +29 -0
  37. package/src/plots/map_plot.ts +46 -0
  38. package/src/plots/pie_plot.ts +23 -0
  39. package/src/plots/scatter_plot.ts +32 -0
  40. package/src/renderers/echarts_map.ts +194 -0
  41. package/src/renderers/echarts_options.ts +317 -0
  42. package/src/renderers/plotly_map.ts +170 -0
  43. package/src/renderers/plotly_options.ts +318 -0
  44. package/src/table/check_column.ts +34 -0
  45. package/src/table/check_values_have_spread.ts +47 -0
  46. package/src/table/compute_quantile.ts +23 -0
  47. package/src/table/data_table.ts +83 -0
  48. package/src/table/density_bandwidth.ts +94 -0
  49. package/src/table/find_line_fit.ts +44 -0
  50. package/src/table/get_number_range.ts +21 -0
  51. package/src/table/group_rows.ts +71 -0
  52. package/src/table/list_categories.ts +17 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Colour scales: how numbers map to colour, shared by charts and maps so
3
+ * `colour_scale` means the same on every plot.
4
+ */
5
+
6
+ import { DEFAULT_COLOUR_SCALE, type ColourScale, type ColourType } from "../fields/colour_fields";
7
+ import { getNumberRange } from "../table/get_number_range";
8
+
9
+ /** Where quantile legends put their labels (0 = lowest, 1 = highest). */
10
+ const QUANTILE_TICKS = [0, 0.25, 0.5, 0.75, 1];
11
+
12
+ /**
13
+ * Write a real value the way legends and hovers show it.
14
+ *
15
+ * @param value - The number.
16
+ * @returns It with thousands separators, or to three significant figures when not whole.
17
+ */
18
+ export function formatValue(value: number): string {
19
+ return Number.isInteger(value) ? value.toLocaleString("en-US") : value.toPrecision(3);
20
+ }
21
+
22
+ /**
23
+ * Turn values into the numbers colour follows, per the layer's colour scale.
24
+ *
25
+ * @param values - The layer's numbers (null where missing).
26
+ * @param options - The scale, the column's name, and where to put notes.
27
+ * @returns The transformed values, and legend ticks in real values when the scale transforms them.
28
+ */
29
+ export function applyColourScale(
30
+ values: (number | null)[],
31
+ options: { scale: ColourScale | undefined; label: string; notes: string[] },
32
+ ): { values: (number | null)[]; ticks: { value: number; text: string }[] | undefined } {
33
+ const scale = options.scale ?? DEFAULT_COLOUR_SCALE;
34
+ if (scale === "linear") return { values, ticks: undefined };
35
+ if (scale === "log") {
36
+ const dropped = values.filter((value) => value !== null && value <= 0).length;
37
+ if (dropped > 0) options.notes.push(`${dropped} value(s) of "${options.label}" are zero or negative, which a log scale cannot show; they are left grey.`);
38
+ const logs = values.map((value) => (value === null || value <= 0 ? null : Math.log10(value)));
39
+ const present = logs.filter((value): value is number => value !== null);
40
+ const ticks: { value: number; text: string }[] = [];
41
+ const logRange = getNumberRange(present);
42
+ for (let power = Math.ceil(logRange.minimum); power <= Math.floor(logRange.maximum); power += 1) ticks.push({ value: power, text: formatValue(10 ** power) });
43
+ return { values: logs, ticks };
44
+ }
45
+ // Quantile: each value becomes its rank from 0 to 1, so colour steps hold equal numbers of places.
46
+ const sorted = values.filter((value): value is number => value !== null).sort((first, second) => first - second);
47
+ // First sorted position of each value, built once; NaN is left out so it ranks -1 like indexOf, which never matches NaN.
48
+ const firstPositions = new Map<number, number>();
49
+ sorted.forEach((value, position) => {
50
+ if (!Number.isNaN(value) && !firstPositions.has(value)) firstPositions.set(value, position);
51
+ });
52
+ const rank = (value: number): number => (sorted.length <= 1 ? 0 : (firstPositions.get(value) ?? -1) / (sorted.length - 1));
53
+ const ticks = QUANTILE_TICKS.map((fraction) => ({ value: fraction, text: formatValue(sorted[Math.round(fraction * (sorted.length - 1))] ?? 0) }));
54
+ return { values: values.map((value) => (value === null ? null : rank(value))), ticks };
55
+ }
56
+
57
+ /**
58
+ * The text at a colour legend's two ends, top first: the real values when
59
+ * the scale transforms them, else the column's name.
60
+ *
61
+ * @param scale - The panel's colour scale.
62
+ * @returns The top and bottom text.
63
+ */
64
+ export function buildColourLegendText(scale: { label: string; ticks?: { value: number; text: string }[] }): [string, string] {
65
+ if (scale.ticks === undefined) return [scale.label, ""];
66
+ return [scale.ticks.at(-1)?.text ?? "", scale.ticks[0]?.text ?? ""];
67
+ }
68
+
69
+ /**
70
+ * Decide whether a column colours by a scale (numbers) or by category: what
71
+ * its values imply, unless colour_type says otherwise.
72
+ *
73
+ * @param values - The colour column's values.
74
+ * @param options - The colour_type the agent sent, if any.
75
+ * @returns True for a colour scale.
76
+ */
77
+ export function decideColourIsContinuous(values: (number | string | null)[], options: { colourType: ColourType | undefined }): boolean {
78
+ if (options.colourType !== undefined) return options.colourType === "continuous";
79
+ return values.every((value) => value === null || typeof value === "number");
80
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Colours and marks for plots, from the dataviz skill's validated reference
3
+ * palette: its dark column for the dark theme, its light column for light.
4
+ *
5
+ * Rules carried over from that skill:
6
+ * - categorical hues are assigned in this fixed order, never cycled or generated;
7
+ * - more than 8 categories is refused (facet or fold to "Other" instead);
8
+ * - where every pair of categories can sit side by side (scatter), only the
9
+ * first 3 hues stay distinguishable, so past 3 the marker shape varies too;
10
+ * - sequential colour is one hue, light to dark; text never wears series colour.
11
+ */
12
+
13
+ import { getNumberRange } from "../table/get_number_range";
14
+
15
+ /** The viewer's two themes; each device picks one. */
16
+ export type PlotTheme = "dark" | "light";
17
+
18
+ /** The theme when none is asked for: the viewer is a dark "TV" by default. */
19
+ export const DEFAULT_PLOT_THEME: PlotTheme = "dark";
20
+
21
+ /** Surface, inks and categorical slots per theme (dataviz reference palette; its light and dark columns). */
22
+ export type ThemeInks = {
23
+ surface: string;
24
+ textPrimary: string;
25
+ textSecondary: string;
26
+ gridLine: string;
27
+ /** Categorical slots 1–8, in the validated order. */
28
+ categorical: readonly string[];
29
+ };
30
+
31
+ /** Each theme's inks: surface, text, grid lines and the categorical colours. */
32
+ export const PLOT_THEMES: Readonly<Record<PlotTheme, ThemeInks>> = {
33
+ dark: {
34
+ surface: "#1a1a19",
35
+ textPrimary: "#ffffff",
36
+ textSecondary: "#c3c2b7",
37
+ gridLine: "#383835",
38
+ categorical: ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767"],
39
+ },
40
+ light: {
41
+ surface: "#fcfcfb",
42
+ textPrimary: "#0b0b0b",
43
+ textSecondary: "#52514e",
44
+ // Recessive grid: the palette's neutral midpoint, a step below the surface.
45
+ gridLine: "#e4e3df",
46
+ categorical: ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#4a3aa7", "#e34948"],
47
+ },
48
+ };
49
+
50
+ /** How many categories colour can tell apart (the palette's slot count). */
51
+ export const MAXIMUM_COLOUR_CATEGORIES = PLOT_THEMES.dark.categorical.length;
52
+
53
+ /** How many categories can share a scatter by colour alone (all-pairs validated). */
54
+ export const ALL_PAIRS_COLOUR_LIMIT = 3;
55
+
56
+ /** The single-hue sequential ramp (blue), light to dark, for continuous colour. */
57
+ export const SEQUENTIAL_COLOURS: readonly string[] = [
58
+ "#cde2fb", "#b7d3f6", "#9ec5f4", "#86b6ef", "#6da7ec", "#5598e7", "#3987e5",
59
+ "#2a78d6", "#256abf", "#1c5cab", "#184f95", "#104281", "#0d366b",
60
+ ];
61
+
62
+ /** Line dash styles, in order, for `line_type` categories. */
63
+ export const LINE_DASHES = ["solid", "dashed", "dotted", "dash_dot"] as const;
64
+ /** A line's dash pattern, one of LINE_DASHES. */
65
+ export type LineDash = (typeof LINE_DASHES)[number];
66
+
67
+ /** Marker shapes, in order, for `marker_shape` categories. */
68
+ export const MARKER_SHAPES = ["circle", "square", "triangle", "diamond", "cross", "star"] as const;
69
+ /** A point's marker shape, one of MARKER_SHAPES. */
70
+ export type MarkerShape = (typeof MARKER_SHAPES)[number];
71
+
72
+ /** Mark sizes from the dataviz skill: 2px lines, markers of at least 8px. */
73
+ export const LINE_WIDTH = 2;
74
+ /** A marker's size in pixels: at least 8 px, so it reads at a glance (dataviz skill). */
75
+ export const MARKER_SIZE = 8;
76
+
77
+ /** Marker sizes for a `size` column, in pixels, smallest to largest. */
78
+ export const SIZE_RANGE_PIXELS = { minimum: MARKER_SIZE, maximum: 28 };
79
+
80
+ /** The thinnest and thickest a map line drawn by a width column is, in pixels. */
81
+ export const LINE_WIDTH_RANGE_PIXELS = { minimum: 1.5, maximum: 8 };
82
+
83
+ /** A map line's width in pixels when the layer has no width column. */
84
+ export const DEFAULT_LINE_WIDTH_PIXELS = 2.5;
85
+
86
+ /**
87
+ * Scale a column's numbers linearly onto a pixel range, smallest to the
88
+ * range's minimum and largest to its maximum. A missing value, or a column
89
+ * whose numbers are all equal, gets the fallback.
90
+ *
91
+ * @param values - The numbers, null where missing.
92
+ * @param options - The pixel range, and the size for a value that cannot be placed on it.
93
+ * @returns A pixel size per value.
94
+ */
95
+ export function scaleToPixels(
96
+ values: readonly (number | null)[],
97
+ options: { range: { minimum: number; maximum: number }; fallback: number },
98
+ ): number[] {
99
+ const present = values.filter((value): value is number => value !== null);
100
+ const { minimum: low, maximum: high } = getNumberRange(present);
101
+ const span = options.range.maximum - options.range.minimum;
102
+ return values.map((value) => (value === null || high === low ? options.fallback : options.range.minimum + ((value - low) / (high - low)) * span));
103
+ }
104
+
105
+ /**
106
+ * Pick the colour for the n-th category.
107
+ *
108
+ * @param index - The category's position in first-seen order (0-based).
109
+ * @param options - The theme it is drawn in.
110
+ * @returns Its hex colour.
111
+ */
112
+ export function pickCategoricalColour(index: number, options: { theme: PlotTheme }): string {
113
+ const colour = PLOT_THEMES[options.theme].categorical[index];
114
+ if (colour === undefined) {
115
+ throw new Error(
116
+ `Colour can tell apart at most ${MAXIMUM_COLOUR_CATEGORIES} categories; got more. ` +
117
+ "Put the rest in an \"Other\" category, or split them across plots in a grid.",
118
+ );
119
+ }
120
+ return colour;
121
+ }
122
+
123
+ /**
124
+ * Pick the dash for the n-th line_type category.
125
+ *
126
+ * @param index - The category's position (0-based).
127
+ * @returns The dash style.
128
+ */
129
+ export function pickLineDash(index: number): LineDash {
130
+ const dash = LINE_DASHES[index];
131
+ if (dash === undefined) {
132
+ throw new Error(`line_type can tell apart at most ${LINE_DASHES.length} categories; got more.`);
133
+ }
134
+ return dash;
135
+ }
136
+
137
+ /**
138
+ * Pick the marker shape for the n-th category.
139
+ *
140
+ * @param index - The category's position (0-based).
141
+ * @returns The shape.
142
+ */
143
+ export function pickMarkerShape(index: number): MarkerShape {
144
+ const shape = MARKER_SHAPES[index];
145
+ if (shape === undefined) {
146
+ throw new Error(`marker_shape can tell apart at most ${MARKER_SHAPES.length} categories; got more.`);
147
+ }
148
+ return shape;
149
+ }
150
+
151
+ /**
152
+ * Pick a colour along the sequential ramp.
153
+ *
154
+ * @param fraction - 0 (lightest) to 1 (darkest); clamped.
155
+ * @returns The nearest ramp step.
156
+ */
157
+ export function pickSequentialColour(fraction: number): string {
158
+ const clamped = Math.min(1, Math.max(0, Number.isFinite(fraction) ? fraction : 0));
159
+ return SEQUENTIAL_COLOURS[Math.round(clamped * (SEQUENTIAL_COLOURS.length - 1))] as string;
160
+ }
161
+
162
+ /** The radix of hexadecimal digits, for colour channels and hashed names. */
163
+ export const HEXADECIMAL = 16;
164
+ const HEXADECIMAL_COLOUR_PATTERN = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
165
+ const CHANNEL_MAXIMUM = 255;
166
+ /** The number of hexadecimal digits in one colour channel of a `#rrggbb` colour. */
167
+ export const CHANNEL_DIGITS = 2;
168
+
169
+ /**
170
+ * Blend a value's colour along a ramp exactly as ECharts' continuous
171
+ * visualMap does (zrender's fastLerp over the ramp's evenly spaced stops,
172
+ * after echarts' clamped linearMap): each channel interpolated between the
173
+ * two nearest stops and rounded. A renderer that paints a colour itself,
174
+ * where a visualMap cannot reach, then matches the colour bar to the byte.
175
+ *
176
+ * @param value - The value to colour.
177
+ * @param options - The scale's range, and the ramp's colours as `#rrggbb`.
178
+ * @returns The colour as `#rrggbb`.
179
+ */
180
+ export function interpolateRampColour(value: number, options: { minimum: number; maximum: number; colours: readonly string[] }): string {
181
+ const span = options.maximum - options.minimum;
182
+ // As echarts' linearMap: a range of no width maps to the middle.
183
+ const fraction = span === 0 ? 1 / 2 : Math.min(1, Math.max(0, (value - options.minimum) / span));
184
+ const position = fraction * (options.colours.length - 1);
185
+ const left = parseHexadecimalColour(options.colours[Math.floor(position)]);
186
+ const right = parseHexadecimalColour(options.colours[Math.ceil(position)]);
187
+ const step = position - Math.floor(position);
188
+ return `#${left.map((from, channel) => {
189
+ const to = right[channel] ?? from;
190
+ const mixed = Math.min(CHANNEL_MAXIMUM, Math.max(0, Math.round(from + (to - from) * step)));
191
+ return mixed.toString(HEXADECIMAL).padStart(CHANNEL_DIGITS, "0");
192
+ }).join("")}`;
193
+ }
194
+
195
+ /**
196
+ * Read a `#rrggbb` colour's channels.
197
+ *
198
+ * @param colour - The colour.
199
+ * @returns Its red, green and blue, 0 to 255.
200
+ */
201
+ function parseHexadecimalColour(colour: string | undefined): number[] {
202
+ const match = HEXADECIMAL_COLOUR_PATTERN.exec(colour ?? "");
203
+ if (match === null) throw new Error(`Expected a ramp colour written #rrggbb; got ${String(colour)}.`);
204
+ return match.slice(1).map((digits) => Number.parseInt(digits, HEXADECIMAL));
205
+ }
206
+
207
+ /** Land, water and borders for maps drawn without street tiles (globe, ECharts), per theme. */
208
+ export const MAP_INKS: Readonly<Record<PlotTheme, { land: string; water: string; border: string }>> = {
209
+ dark: { land: "#2a2b2f", water: "#141518", border: "#4a4b51" },
210
+ light: { land: "#fcfcfb", water: "#e9edf1", border: "#c9c8c2" },
211
+ };
212
+
213
+ /** The font OpenFreeMap serves for map labels; any other font's glyphs 404 on its server. */
214
+ export const MAP_LABEL_FONT = "Noto Sans Regular";
215
+
216
+ /** The street-map style (OpenFreeMap: free, no key; attribution is added by the map library) per theme. */
217
+ export const MAP_STYLE_URLS: Readonly<Record<PlotTheme, string>> = {
218
+ dark: "https://tiles.openfreemap.org/styles/dark",
219
+ light: "https://tiles.openfreemap.org/styles/positron",
220
+ };
@@ -0,0 +1,320 @@
1
+ /**
2
+ * One example of every plot type, each in a simple form (the type at its
3
+ * plainest: one line, one set of bars) and a complex one (several series
4
+ * in colour, and the type's own options). They show an agent, a reader of
5
+ * the docs, or the gallery page what each type can do, and the tests check
6
+ * every one is a valid figure.
7
+ *
8
+ * The data is realistic but approximate (rounded climate normals and
9
+ * populations); where a type needs many values (a histogram, a density),
10
+ * they come from a fixed-seed generator, so the examples never change.
11
+ */
12
+
13
+ import type { PlotFigureInput, PlotType } from "../figure/plot_figure";
14
+ import { findColumn, type DataTable } from "../table/data_table";
15
+
16
+ /** One plot type's two examples. */
17
+ export type ExampleFigures = { type: PlotType; name: string; simple: PlotFigureInput; complex: PlotFigureInput };
18
+
19
+ // ── Generated values: a seeded generator, so the examples are fixed ──────
20
+
21
+ /** Park and Miller's minimal standard generator: multiplier and modulus (a 31-bit prime). */
22
+ const GENERATOR_MULTIPLIER = 16807;
23
+ const GENERATOR_MODULUS = 2147483647;
24
+ /** Any fixed seed works; this one is the example data's. */
25
+ const EXAMPLE_SEED = 20261001;
26
+
27
+ /**
28
+ * Make a generator of values spread like a bell curve (Box and Muller), from a fixed seed.
29
+ *
30
+ * @param seed - The starting state.
31
+ * @returns A function giving the next value, for a mean and a spread.
32
+ */
33
+ function createNormalGenerator(seed: number): (spread: { mean: number; deviation: number }) => number {
34
+ let state = seed % GENERATOR_MODULUS;
35
+ const nextUniform = (): number => {
36
+ state = (state * GENERATOR_MULTIPLIER) % GENERATOR_MODULUS;
37
+ return state / GENERATOR_MODULUS;
38
+ };
39
+ return ({ mean, deviation }) => {
40
+ const radius = Math.sqrt(-2 * Math.log(nextUniform()));
41
+ return mean + deviation * radius * Math.cos(2 * Math.PI * nextUniform());
42
+ };
43
+ }
44
+
45
+ /** Values rounded to one decimal place, for tidy tooltips. */
46
+ function roundToTenths(value: number): number {
47
+ return Math.round(value * 10) / 10;
48
+ }
49
+
50
+ /**
51
+ * Keep the largest rows of a table and sum the rest into one "Other" row: how
52
+ * a pie with more slices than colours is drawn.
53
+ *
54
+ * @param table - The table.
55
+ * @param options - The label and value columns, and how many rows to keep.
56
+ * @returns A table of just those two columns.
57
+ */
58
+ function buildLargestWithOther(table: DataTable, options: { label: string; value: string; kept: number }): DataTable {
59
+ const rows = (findColumn(table, { column: options.label }) ?? []).map((label, index) => ({ label, value: Number(findColumn(table, { column: options.value })?.[index] ?? 0) }));
60
+ rows.sort((first, second) => second.value - first.value);
61
+ const kept = rows.slice(0, options.kept);
62
+ const other = rows.slice(options.kept).reduce((sum, row) => sum + row.value, 0);
63
+ return { [options.label]: [...kept.map((row) => row.label), "Other"], [options.value]: [...kept.map((row) => row.value), other] };
64
+ }
65
+
66
+ // ── Shared tables ─────────────────────────────────────────────────────────
67
+
68
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
69
+
70
+ /** Average daily high, °C, by month (rounded climate normals). */
71
+ const MONTHLY_HIGHS: Record<string, number[]> = {
72
+ Toronto: [-1, 0, 5, 12, 19, 24, 27, 26, 22, 14, 8, 2],
73
+ Vancouver: [7, 8, 10, 13, 17, 19, 22, 22, 19, 14, 9, 6],
74
+ Montreal: [-5, -3, 3, 11, 19, 24, 26, 25, 20, 13, 5, -2],
75
+ Halifax: [0, 0, 4, 9, 15, 20, 24, 24, 20, 14, 8, 3],
76
+ };
77
+
78
+ /** Every city's monthly highs in one long table: month, city, high. */
79
+ function buildMonthlyHighsTable(): DataTable {
80
+ const table: DataTable = { month: [], city: [], high_c: [] };
81
+ for (const [city, highs] of Object.entries(MONTHLY_HIGHS)) {
82
+ highs.forEach((high, index) => {
83
+ table.month?.push(MONTHS[index] ?? null);
84
+ table.city?.push(city);
85
+ table.high_c?.push(high);
86
+ });
87
+ }
88
+ return table;
89
+ }
90
+
91
+ /** Palmer penguins, a sample: species, island, flipper length and body mass. */
92
+ const PENGUINS: DataTable = {
93
+ species: ["Adelie", "Adelie", "Adelie", "Adelie", "Adelie", "Gentoo", "Gentoo", "Gentoo", "Gentoo", "Gentoo", "Chinstrap", "Chinstrap", "Chinstrap", "Chinstrap", "Chinstrap"],
94
+ island: ["Torgersen", "Biscoe", "Dream", "Torgersen", "Dream", "Biscoe", "Biscoe", "Biscoe", "Biscoe", "Biscoe", "Dream", "Dream", "Dream", "Dream", "Dream"],
95
+ flipper_mm: [181, 186, 195, 193, 190, 211, 230, 218, 215, 222, 192, 196, 193, 188, 201],
96
+ mass_g: [3750, 3800, 3250, 3450, 3650, 4500, 5700, 4450, 5550, 5000, 3500, 3900, 3650, 3525, 3950],
97
+ bill_mm: [39.1, 39.5, 40.3, 36.7, 39.3, 46.1, 50.0, 48.7, 50.0, 47.6, 46.5, 50.0, 51.3, 45.4, 52.7],
98
+ };
99
+
100
+ /** Canadian cities: where they are, their province and their population (2021 census, rounded). */
101
+ const CANADIAN_CITIES: DataTable = {
102
+ city: ["Toronto", "Montreal", "Vancouver", "Calgary", "Edmonton", "Ottawa", "Winnipeg", "Quebec City", "Halifax", "Victoria"],
103
+ province: ["Ontario", "Quebec", "British Columbia", "Alberta", "Alberta", "Ontario", "Manitoba", "Quebec", "Nova Scotia", "British Columbia"],
104
+ longitude: [-79.38, -73.57, -123.12, -114.07, -113.49, -75.70, -97.14, -71.21, -63.57, -123.37],
105
+ latitude: [43.65, 45.50, 49.28, 51.05, 53.55, 45.42, 49.90, 46.81, 44.65, 48.43],
106
+ population: [2794356, 1762949, 662248, 1306784, 1010899, 1017449, 749607, 549459, 439819, 91867],
107
+ };
108
+
109
+ /** A shop's sales by quarter and region, thousands of dollars. */
110
+ const QUARTERLY_SALES: DataTable = {
111
+ quarter: ["Q1", "Q2", "Q3", "Q4", "Q1", "Q2", "Q3", "Q4", "Q1", "Q2", "Q3", "Q4", "Q1", "Q2", "Q3", "Q4"],
112
+ region: ["North", "North", "North", "North", "South", "South", "South", "South", "East", "East", "East", "East", "West", "West", "West", "West"],
113
+ sales_thousands: [120, 135, 160, 210, 90, 110, 105, 150, 140, 150, 170, 230, 80, 95, 120, 140],
114
+ };
115
+
116
+ /** Population of the 27 EU countries, millions (2023 estimates, rounded). */
117
+ const EU_POPULATIONS: DataTable = {
118
+ country: ["Germany", "France", "Italy", "Spain", "Poland", "Romania", "Netherlands", "Belgium", "Czechia", "Sweden", "Portugal", "Greece", "Hungary", "Austria", "Bulgaria", "Denmark", "Finland", "Slovakia", "Ireland", "Croatia", "Lithuania", "Slovenia", "Latvia", "Estonia", "Cyprus", "Luxembourg", "Malta"],
119
+ population_millions: [84.4, 68.2, 59.0, 48.1, 36.8, 19.1, 17.9, 11.8, 10.8, 10.6, 10.5, 10.4, 9.6, 9.1, 6.4, 5.9, 5.6, 5.4, 5.3, 3.9, 2.9, 2.1, 1.9, 1.4, 0.9, 0.7, 0.5],
120
+ };
121
+
122
+ /** Population of the 50 US states and the District of Columbia, millions (2020 census). */
123
+ const STATE_POPULATIONS: DataTable = {
124
+ state: ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"],
125
+ population_millions: [5.02, 0.73, 7.15, 3.01, 39.54, 5.77, 3.61, 0.99, 0.69, 21.54, 10.71, 1.46, 1.84, 12.81, 6.79, 3.19, 2.94, 4.51, 4.66, 1.36, 6.18, 7.03, 10.08, 5.71, 2.96, 6.15, 1.08, 1.96, 3.1, 1.38, 9.29, 2.12, 20.2, 10.44, 0.78, 11.8, 3.96, 4.24, 13.0, 1.1, 5.12, 0.89, 6.91, 29.15, 3.27, 0.64, 8.63, 7.71, 1.79, 5.89, 0.58],
126
+ };
127
+
128
+ // ── The examples, one per type ───────────────────────────────────────────
129
+
130
+ /**
131
+ * Build every plot type's simple and complex example.
132
+ *
133
+ * @returns One entry per plot type, in the order the types are listed.
134
+ */
135
+ export function buildExampleFigures(): ExampleFigures[] {
136
+ const nextNormal = createNormalGenerator(EXAMPLE_SEED);
137
+ const monthlyHighs = buildMonthlyHighsTable();
138
+ const torontoHighs = { month: MONTHS, high_c: MONTHLY_HIGHS.Toronto ?? [] };
139
+
140
+ // Heights (cm) of three groups of adults, for the histogram and the density plot.
141
+ const heightGroups = [
142
+ { group: "Netherlands", mean: 182.5, deviation: 7 },
143
+ { group: "Canada", mean: 176, deviation: 7 },
144
+ { group: "Peru", mean: 165.5, deviation: 6.5 },
145
+ ];
146
+ const heights: DataTable = { country: [], height_cm: [] };
147
+ for (const { group, mean, deviation } of heightGroups) {
148
+ for (let index = 0; index < 120; index += 1) {
149
+ heights.country?.push(group);
150
+ heights.height_cm?.push(roundToTenths(nextNormal({ mean, deviation })));
151
+ }
152
+ }
153
+ const dutchHeights = { height_cm: heights.height_cm?.filter((_, index) => heights.country?.[index] === "Netherlands") ?? [] };
154
+
155
+ // Visits to a park by weekday and hour, for the heatmap: busiest at midday, busier at the weekend.
156
+ const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
157
+ const hours = ["6:00", "8:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00"];
158
+ const visits: DataTable = { weekday: [], hour: [], visits: [] };
159
+ weekdays.forEach((weekday, dayIndex) => {
160
+ hours.forEach((hour, hourIndex) => {
161
+ const midday = 1 - Math.abs(hourIndex - 3.5) / 4;
162
+ const weekend = dayIndex >= 5 ? 1.4 : 1;
163
+ visits.weekday?.push(weekday);
164
+ visits.hour?.push(hour);
165
+ visits.visits?.push(Math.round(40 + 160 * midday * weekend + nextNormal({ mean: 0, deviation: 8 })));
166
+ });
167
+ });
168
+
169
+ return [
170
+ {
171
+ type: "line",
172
+ name: "Line",
173
+ simple: { title: "Toronto: average daily high", data: torontoHighs, plots: [{ type: "line", x: "month", y: "high_c", y_label: "°C" }] },
174
+ complex: {
175
+ title: "Average daily high in four Canadian cities",
176
+ data: monthlyHighs,
177
+ plots: [{ type: "line", x: "month", y: "high_c", colour: "city", show_markers: true, y_label: "°C" }],
178
+ },
179
+ },
180
+ {
181
+ type: "scatter",
182
+ name: "Scatter",
183
+ simple: { title: "Penguins: flipper length and body mass", data: PENGUINS, plots: [{ type: "scatter", x: "flipper_mm", y: "mass_g", x_label: "Flipper (mm)", y_label: "Mass (g)" }] },
184
+ complex: {
185
+ title: "Penguins by species, sized by bill length, with a trend line",
186
+ data: PENGUINS,
187
+ plots: [{ type: "scatter", x: "flipper_mm", y: "mass_g", colour: "species", size: "bill_mm", show_trend_line: true, x_label: "Flipper (mm)", y_label: "Mass (g)" }],
188
+ },
189
+ },
190
+ {
191
+ type: "bar",
192
+ name: "Bar",
193
+ simple: { title: "Toronto: average daily high", data: torontoHighs, plots: [{ type: "bar", x: "month", y: "high_c", y_label: "°C" }] },
194
+ complex: {
195
+ title: "Sales by quarter and region: side by side, and stacked",
196
+ grid: { rows: 1, columns: 2 },
197
+ data: QUARTERLY_SALES,
198
+ plots: [
199
+ { type: "bar", x: "quarter", y: "sales_thousands", colour: "region", mode: "grouped", y_label: "Sales ($ thousands)" },
200
+ { type: "bar", x: "region", y: "sales_thousands", colour: "quarter", mode: "stacked", orientation: "horizontal", y_label: "Sales ($ thousands)" },
201
+ ],
202
+ },
203
+ },
204
+ {
205
+ type: "box",
206
+ name: "Box",
207
+ simple: { title: "Penguin body mass", data: PENGUINS, plots: [{ type: "box", y: "mass_g", y_label: "Mass (g)" }] },
208
+ complex: {
209
+ title: "Penguin body mass by species, with every penguin shown",
210
+ data: PENGUINS,
211
+ plots: [{ type: "box", x: "species", y: "mass_g", colour: "species", show_markers: true, y_label: "Mass (g)" }],
212
+ },
213
+ },
214
+ {
215
+ type: "histogram",
216
+ name: "Histogram",
217
+ simple: { title: "Heights of Dutch adults", data: dutchHeights, plots: [{ type: "histogram", x: "height_cm", x_label: "Height (cm)" }] },
218
+ complex: {
219
+ title: "Heights in three countries, as shares of each",
220
+ data: heights,
221
+ plots: [{ type: "histogram", x: "height_cm", colour: "country", bins: 30, is_normalised: true, x_label: "Height (cm)" }],
222
+ },
223
+ },
224
+ {
225
+ type: "density",
226
+ name: "Density",
227
+ simple: { title: "Heights of Dutch adults", data: dutchHeights, plots: [{ type: "density", x: "height_cm", x_label: "Height (cm)" }] },
228
+ complex: {
229
+ title: "Heights in three countries, filled",
230
+ data: heights,
231
+ plots: [{ type: "density", x: "height_cm", colour: "country", show_area: true, x_label: "Height (cm)" }],
232
+ },
233
+ },
234
+ {
235
+ type: "heatmap",
236
+ name: "Heatmap",
237
+ simple: {
238
+ title: "Average daily high by city and month",
239
+ data: monthlyHighs,
240
+ plots: [{ type: "heatmap", x: "month", y: "city", value: "high_c" }],
241
+ },
242
+ complex: {
243
+ title: "Visits to a park by weekday and hour, in a sequential scale",
244
+ data: visits,
245
+ plots: [{ type: "heatmap", x: "hour", y: "weekday", value: "visits", x_label: "Hour", y_label: "Day" }],
246
+ },
247
+ },
248
+ {
249
+ type: "pie",
250
+ name: "Pie",
251
+ simple: {
252
+ title: "Population of Canadian cities",
253
+ data: { city: CANADIAN_CITIES.city?.slice(0, 5) ?? [], population: CANADIAN_CITIES.population?.slice(0, 5) ?? [] },
254
+ plots: [{ type: "pie", label: "city", value: "population" }],
255
+ },
256
+ complex: {
257
+ title: "Ten Canadian cities: the seven largest, and the rest",
258
+ data: buildLargestWithOther(CANADIAN_CITIES, { label: "city", value: "population", kept: 7 }),
259
+ plots: [{ type: "pie", label: "city", value: "population", hole: 0.55 }],
260
+ },
261
+ },
262
+ {
263
+ type: "map",
264
+ name: "Map",
265
+ simple: {
266
+ title: "Canadian cities",
267
+ data: CANADIAN_CITIES,
268
+ plots: [{ type: "map", layers: [{ type: "points", longitude: "longitude", latitude: "latitude", label: "city" }] }],
269
+ },
270
+ complex: {
271
+ title: "Cities by province and size, with flights from Toronto",
272
+ data: CANADIAN_CITIES,
273
+ plots: [{
274
+ type: "map",
275
+ layers: [
276
+ {
277
+ type: "lines", from_longitude: "from_longitude", from_latitude: "from_latitude", to_longitude: "longitude", to_latitude: "latitude", label: "city",
278
+ data: {
279
+ city: CANADIAN_CITIES.city?.slice(1) ?? [],
280
+ from_longitude: (CANADIAN_CITIES.city?.slice(1) ?? []).map(() => CANADIAN_CITIES.longitude?.[0] ?? null),
281
+ from_latitude: (CANADIAN_CITIES.city?.slice(1) ?? []).map(() => CANADIAN_CITIES.latitude?.[0] ?? null),
282
+ longitude: CANADIAN_CITIES.longitude?.slice(1) ?? [],
283
+ latitude: CANADIAN_CITIES.latitude?.slice(1) ?? [],
284
+ },
285
+ },
286
+ { type: "points", longitude: "longitude", latitude: "latitude", label: "city", colour: "province", size: "population" },
287
+ ],
288
+ }],
289
+ },
290
+ },
291
+ {
292
+ type: "map",
293
+ name: "Map of regions",
294
+ simple: {
295
+ title: "Population of the EU countries (millions)",
296
+ data: EU_POPULATIONS,
297
+ plots: [{ type: "map", layers: [{ type: "regions", boundaries: "eu_countries", key: "country", value: "population_millions" }] }],
298
+ },
299
+ complex: {
300
+ title: "Population by US state (millions), on a log scale",
301
+ data: STATE_POPULATIONS,
302
+ plots: [{ type: "map", layers: [{ type: "regions", boundaries: "us_states", key: "state", value: "population_millions", colour_scale: "log" }] }],
303
+ },
304
+ },
305
+ {
306
+ type: "map",
307
+ name: "Globe and density",
308
+ simple: {
309
+ title: "Where Canadians live: the density of its cities",
310
+ data: CANADIAN_CITIES,
311
+ plots: [{ type: "map", layers: [{ type: "density", longitude: "longitude", latitude: "latitude", weight: "population" }] }],
312
+ },
313
+ complex: {
314
+ title: "Canadian cities on a globe, sized by population",
315
+ data: CANADIAN_CITIES,
316
+ plots: [{ type: "map", projection: "globe", layers: [{ type: "points", longitude: "longitude", latitude: "latitude", label: "city", colour: "population", colour_type: "continuous", size: "population" }] }],
317
+ },
318
+ },
319
+ ];
320
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The fields of every plot drawn on x and y axes. Each describes its column,
3
+ * whatever the orientation: on horizontal bars, x_label titles the vertical
4
+ * axis, because that is where x is drawn.
5
+ */
6
+
7
+ import { z } from "zod";
8
+
9
+ /** How an axis may space numbers. */
10
+ export const AXIS_SCALES = ["linear", "log"] as const;
11
+ /** One of AXIS_SCALES. */
12
+ export type AxisScale = (typeof AXIS_SCALES)[number];
13
+ /** The scale an axis gets when the agent names none. */
14
+ export const DEFAULT_AXIS_SCALE: AxisScale = "linear";
15
+
16
+ const AXIS_SCALE_SCHEMA = z.enum(AXIS_SCALES).default(DEFAULT_AXIS_SCALE);
17
+
18
+ /** The axis titles, on every plot drawn on axes. */
19
+ export const AXIS_LABEL_FIELDS = {
20
+ x_label: z.string().min(1).optional().describe("The title of the axis the x column is drawn on. Default: the x column's name."),
21
+ y_label: z.string().min(1).optional().describe("The title of the axis the y column is drawn on. Default: the y column's name."),
22
+ };
23
+
24
+ /** The x column's scale: only on plots whose x axis can space numbers (a bar's or a box's x is categories, a histogram's x is equal bins). */
25
+ export const X_SCALE_FIELDS = {
26
+ x_scale: AXIS_SCALE_SCHEMA.describe("How the x column's axis spaces numbers: evenly, or by order of magnitude."),
27
+ };
28
+
29
+ /** The y column's scale: only on plots whose y is numbers (a heatmap's y is categories, so it refuses it). */
30
+ export const Y_SCALE_FIELDS = {
31
+ y_scale: AXIS_SCALE_SCHEMA.describe("How the y column's axis spaces numbers: evenly, or by order of magnitude."),
32
+ };