plotilla 0.2.0 → 1.1.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 (155) hide show
  1. package/README.md +37 -11
  2. package/data/boundaries/world_countries.geojson +1 -1
  3. package/dist/colour/colour_scale.d.ts +55 -0
  4. package/dist/colour/colour_scale.js +80 -0
  5. package/dist/colour/palette.d.ts +176 -0
  6. package/dist/colour/palette.js +220 -0
  7. package/dist/fields/axis_fields.d.ts +56 -0
  8. package/dist/fields/axis_fields.js +46 -0
  9. package/dist/fields/colour_fields.d.ts +32 -0
  10. package/dist/fields/colour_fields.js +31 -0
  11. package/dist/fields/column_fields.d.ts +52 -0
  12. package/{src/fields/column_fields.ts → dist/fields/column_fields.js} +15 -29
  13. package/dist/fields/common_fields.d.ts +9 -0
  14. package/{src/fields/common_fields.ts → dist/fields/common_fields.js} +3 -6
  15. package/dist/fields/decide_plot_axes.d.ts +56 -0
  16. package/dist/fields/decide_plot_axes.js +71 -0
  17. package/dist/fields/marker_fields.d.ts +8 -0
  18. package/dist/fields/marker_fields.js +13 -0
  19. package/dist/fields/read_date_time.d.ts +85 -0
  20. package/dist/fields/read_date_time.js +199 -0
  21. package/dist/figure/check_axis_year_formats.d.ts +36 -0
  22. package/dist/figure/check_axis_year_formats.js +116 -0
  23. package/dist/figure/check_plot_category_limits.d.ts +128 -0
  24. package/dist/figure/check_plot_category_limits.js +284 -0
  25. package/dist/figure/plot_figure.d.ts +861 -0
  26. package/dist/figure/plot_figure.js +58 -0
  27. package/dist/figure/resolve_plot_figure.d.ts +28 -0
  28. package/dist/figure/resolve_plot_figure.js +41 -0
  29. package/dist/figure/validate_plot_figure.d.ts +50 -0
  30. package/dist/figure/validate_plot_figure.js +441 -0
  31. package/dist/map/assign_map_layer_hue_slots.d.ts +89 -0
  32. package/dist/map/assign_map_layer_hue_slots.js +146 -0
  33. package/dist/map/boundary_sets.d.ts +65 -0
  34. package/dist/map/boundary_sets.js +103 -0
  35. package/dist/map/build_world_outline_across_180.d.ts +21 -0
  36. package/dist/map/build_world_outline_across_180.js +23 -0
  37. package/dist/map/check_map_layers.d.ts +16 -0
  38. package/dist/map/check_map_layers.js +31 -0
  39. package/dist/map/fetch_region_outlines.d.ts +25 -0
  40. package/dist/map/fetch_region_outlines.js +39 -0
  41. package/dist/map/geojson.d.ts +150 -0
  42. package/dist/map/geojson.js +248 -0
  43. package/dist/map/join_region_rows.d.ts +40 -0
  44. package/dist/map/join_region_rows.js +45 -0
  45. package/dist/map/map_layers.d.ts +229 -0
  46. package/dist/map/map_layers.js +87 -0
  47. package/dist/model/find_panel_colour_scale.d.ts +25 -0
  48. package/dist/model/find_panel_colour_scale.js +27 -0
  49. package/dist/model/map_model.d.ts +30 -0
  50. package/dist/model/map_model.js +234 -0
  51. package/dist/model/panel_layout.d.ts +42 -0
  52. package/dist/model/panel_layout.js +154 -0
  53. package/dist/model/panel_model.d.ts +223 -0
  54. package/dist/model/panel_model.js +7 -0
  55. package/dist/model/plot_model.d.ts +28 -0
  56. package/dist/model/plot_model.js +431 -0
  57. package/dist/model/statistics.d.ts +83 -0
  58. package/dist/model/statistics.js +107 -0
  59. package/dist/plots/bar_plot.d.ts +46 -0
  60. package/dist/plots/bar_plot.js +30 -0
  61. package/dist/plots/box_plot.d.ts +30 -0
  62. package/dist/plots/box_plot.js +21 -0
  63. package/dist/plots/density_plot.d.ts +36 -0
  64. package/dist/plots/density_plot.js +23 -0
  65. package/dist/plots/heatmap_plot.d.ts +22 -0
  66. package/dist/plots/heatmap_plot.js +18 -0
  67. package/dist/plots/histogram_plot.d.ts +32 -0
  68. package/dist/plots/histogram_plot.js +24 -0
  69. package/dist/plots/line_plot.d.ts +44 -0
  70. package/dist/plots/line_plot.js +25 -0
  71. package/dist/plots/map_plot.d.ts +92 -0
  72. package/dist/plots/map_plot.js +35 -0
  73. package/dist/plots/pie_plot.d.ts +17 -0
  74. package/dist/plots/pie_plot.js +16 -0
  75. package/dist/plots/scatter_plot.d.ts +47 -0
  76. package/dist/plots/scatter_plot.js +27 -0
  77. package/dist/renderers/date_ticks.d.ts +37 -0
  78. package/dist/renderers/date_ticks.js +148 -0
  79. package/dist/renderers/echarts_map.d.ts +47 -0
  80. package/dist/renderers/echarts_map.js +492 -0
  81. package/dist/renderers/echarts_options.d.ts +30 -0
  82. package/dist/renderers/echarts_options.js +449 -0
  83. package/dist/renderers/echarts_pie_radius.d.ts +52 -0
  84. package/dist/renderers/echarts_pie_radius.js +158 -0
  85. package/dist/renderers/escape_html.d.ts +10 -0
  86. package/dist/renderers/escape_html.js +15 -0
  87. package/dist/renderers/line_colour_segments.d.ts +39 -0
  88. package/dist/renderers/line_colour_segments.js +41 -0
  89. package/dist/renderers/plotly_map.d.ts +48 -0
  90. package/dist/renderers/plotly_map.js +159 -0
  91. package/dist/renderers/plotly_options.d.ts +19 -0
  92. package/dist/renderers/plotly_options.js +345 -0
  93. package/dist/renderers/year_ticks.d.ts +27 -0
  94. package/dist/renderers/year_ticks.js +42 -0
  95. package/dist/table/check_column.d.ts +36 -0
  96. package/dist/table/check_column.js +46 -0
  97. package/dist/table/check_values_have_spread.d.ts +30 -0
  98. package/{src/table/check_values_have_spread.ts → dist/table/check_values_have_spread.js} +16 -17
  99. package/dist/table/compute_quantile.d.ts +16 -0
  100. package/dist/table/compute_quantile.js +23 -0
  101. package/dist/table/data_table.d.ts +59 -0
  102. package/dist/table/data_table.js +87 -0
  103. package/dist/table/density_bandwidth.d.ts +64 -0
  104. package/dist/table/density_bandwidth.js +88 -0
  105. package/dist/table/find_line_fit.d.ts +30 -0
  106. package/dist/table/find_line_fit.js +36 -0
  107. package/dist/table/get_number_range.d.ts +16 -0
  108. package/{src/table/get_number_range.ts → dist/table/get_number_range.js} +8 -8
  109. package/dist/table/group_rows.d.ts +40 -0
  110. package/dist/table/group_rows.js +67 -0
  111. package/dist/table/list_categories.d.ts +14 -0
  112. package/{src/table/list_categories.ts → dist/table/list_categories.js} +2 -3
  113. package/dist/table/read_number.d.ts +12 -0
  114. package/dist/table/read_number.js +14 -0
  115. package/package.json +30 -25
  116. package/src/colour/colour_scale.ts +0 -80
  117. package/src/colour/palette.ts +0 -220
  118. package/src/examples/example_figures.ts +0 -320
  119. package/src/fields/axis_fields.ts +0 -32
  120. package/src/fields/colour_fields.ts +0 -40
  121. package/src/fields/decide_plot_axes.ts +0 -77
  122. package/src/fields/marker_fields.ts +0 -16
  123. package/src/figure/plot_figure.ts +0 -67
  124. package/src/figure/resolve_plot_figure.ts +0 -47
  125. package/src/figure/validate_plot_figure.ts +0 -412
  126. package/src/map/boundary_sets.ts +0 -116
  127. package/src/map/check_map_layers.ts +0 -32
  128. package/src/map/fetch_region_outlines.ts +0 -48
  129. package/src/map/geojson.ts +0 -174
  130. package/src/map/map_layers.ts +0 -108
  131. package/src/model/check_axis_shows_years.ts +0 -58
  132. package/src/model/map_model.ts +0 -238
  133. package/src/model/panel_layout.ts +0 -171
  134. package/src/model/panel_model.ts +0 -85
  135. package/src/model/plot_model.ts +0 -347
  136. package/src/model/statistics.ts +0 -134
  137. package/src/plots/bar_plot.ts +0 -36
  138. package/src/plots/box_plot.ts +0 -26
  139. package/src/plots/density_plot.ts +0 -29
  140. package/src/plots/heatmap_plot.ts +0 -24
  141. package/src/plots/histogram_plot.ts +0 -29
  142. package/src/plots/line_plot.ts +0 -29
  143. package/src/plots/map_plot.ts +0 -46
  144. package/src/plots/pie_plot.ts +0 -23
  145. package/src/plots/scatter_plot.ts +0 -32
  146. package/src/renderers/echarts_map.ts +0 -194
  147. package/src/renderers/echarts_options.ts +0 -317
  148. package/src/renderers/plotly_map.ts +0 -170
  149. package/src/renderers/plotly_options.ts +0 -318
  150. package/src/table/check_column.ts +0 -34
  151. package/src/table/compute_quantile.ts +0 -23
  152. package/src/table/data_table.ts +0 -83
  153. package/src/table/density_bandwidth.ts +0 -94
  154. package/src/table/find_line_fit.ts +0 -44
  155. package/src/table/group_rows.ts +0 -71
@@ -1,320 +0,0 @@
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
- }
@@ -1,32 +0,0 @@
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
- };
@@ -1,40 +0,0 @@
1
- /**
2
- * The fields of plots coloured by a column. A plot that can colour by a
3
- * number also takes COLOUR_SCALE_FIELDS; one without them colours by
4
- * category only, and validation refuses a numeric colour there.
5
- */
6
-
7
- import { z } from "zod";
8
- import { defineColumnField } from "./column_fields";
9
-
10
- /** Whether a colouring column's values are categories or a scale. */
11
- export const COLOUR_TYPES = ["categorical", "continuous"] as const;
12
- /** One of COLOUR_TYPES. */
13
- export type ColourType = (typeof COLOUR_TYPES)[number];
14
- /** How numbers may map to colour, on charts and maps alike. */
15
- export const COLOUR_SCALES = ["linear", "log", "quantile"] as const;
16
- /** One of COLOUR_SCALES. */
17
- export type ColourScale = (typeof COLOUR_SCALES)[number];
18
- /** The colour scale a plot gets when the agent names none. */
19
- export const DEFAULT_COLOUR_SCALE: ColourScale = "linear";
20
-
21
- /** The fields of a plot or layer coloured by a column. */
22
- export const COLOUR_FIELDS = {
23
- colour: defineColumnField("The column that colours the marks: text gives a colour per category, numbers a colour scale.").optional(),
24
- colour_type: z
25
- .enum(COLOUR_TYPES)
26
- .optional()
27
- .describe('Overrides what the colouring column\'s values imply (colour, or a map region\'s value), e.g. "categorical" for numbered years.'),
28
- };
29
-
30
- /** The scales, written for an error: "linear", "log" or "quantile". */
31
- const COLOUR_SCALE_CHOICES = `${COLOUR_SCALES.slice(0, -1).map((scale) => `"${scale}"`).join(", ")} or "${COLOUR_SCALES.at(-1)}"`;
32
-
33
- /** The field of a plot or layer that can colour by a number. */
34
- export const COLOUR_SCALE_FIELDS = {
35
- colour_scale: z
36
- .enum(COLOUR_SCALES, { error: (issue) => `${COLOUR_SCALE_CHOICES}; got ${JSON.stringify(issue.input)}.` })
37
- // No schema default: a scale sent where colour is not a scale is refused, which needs "not sent" apart from "linear".
38
- .optional()
39
- .describe("How numbers map to colour: evenly, by order of magnitude, or by rank so each step holds as many marks. Default: linear. Only with a colour of numbers."),
40
- };
@@ -1,77 +0,0 @@
1
- /**
2
- * Which axes a plot has, and of what kind and scale. One rule, read by the
3
- * model to build each axis and by validation to judge shared axes, so a
4
- * figure is never refused or accepted on axes the model would not draw.
5
- * It sits in `fields`, below both `figure` and `model`, as `listMarkColumns` does.
6
- */
7
-
8
- import { findColumn, type DataTable } from "../table/data_table";
9
- import { DEFAULT_AXIS_SCALE, type AxisScale } from "./axis_fields";
10
-
11
- /** How an axis places values: spaced numbers, named categories, or dates. */
12
- export type AxisKind = "value" | "category" | "time";
13
-
14
- /** An axis's kind and scale: what decides whether two axes can be linked. */
15
- export type PlotAxis = { kind: AxisKind; scale: AxisScale };
16
-
17
- /** A plot's axes; null where it has none (a pie, a map). */
18
- export type PlotAxes = { x: PlotAxis | null; y: PlotAxis | null };
19
-
20
- /** A date, or a date and time, as ISO 8601 writes it (2025-01-01, 2025-01-01T08:30Z). */
21
- const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}([T ][\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/;
22
-
23
- /** A category axis spaces nothing, so its scale is always the default. */
24
- const CATEGORY_AXIS: PlotAxis = { kind: "category", scale: DEFAULT_AXIS_SCALE };
25
-
26
- /**
27
- * Decide an axis's kind from the values of its column: numbers are a value
28
- * axis, ISO dates a time axis, anything else categories.
29
- *
30
- * @param values - The column's values.
31
- * @returns The axis kind.
32
- */
33
- export function decideAxisKind(values: readonly (number | string | null)[]): AxisKind {
34
- const present = values.filter((value) => value !== null);
35
- if (present.every((value) => typeof value === "number")) return "value";
36
- if (present.every((value) => typeof value === "string" && ISO_DATE_PATTERN.test(value))) return "time";
37
- return "category";
38
- }
39
-
40
- /**
41
- * Decide a plot's axes. Bars, boxes and heatmaps put categories on their
42
- * category axis (a horizontal bar's is y); histograms and densities count
43
- * numbers in x; lines and scatters take x's kind from its column.
44
- *
45
- * @param plot - The plot's type and its axis fields.
46
- * @param options - The table the plot draws from.
47
- * @returns Its x and y axes, null where it has none.
48
- */
49
- export function decidePlotAxes(
50
- plot: { type: string; x?: string; x_scale?: AxisScale; y_scale?: AxisScale; orientation?: string },
51
- options: { table: DataTable },
52
- ): PlotAxes {
53
- const xScale = plot.x_scale ?? DEFAULT_AXIS_SCALE;
54
- const yScale = plot.y_scale ?? DEFAULT_AXIS_SCALE;
55
- const valueY: PlotAxis = { kind: "value", scale: yScale };
56
- switch (plot.type) {
57
- case "line":
58
- case "scatter": {
59
- const xValues = plot.x === undefined ? [] : (findColumn(options.table, { column: plot.x }) ?? []);
60
- return { x: { kind: decideAxisKind(xValues), scale: xScale }, y: valueY };
61
- }
62
- case "bar":
63
- return plot.orientation === "horizontal" ? { x: valueY, y: CATEGORY_AXIS } : { x: CATEGORY_AXIS, y: valueY };
64
- case "box":
65
- return { x: CATEGORY_AXIS, y: valueY };
66
- case "histogram":
67
- case "density":
68
- return { x: { kind: "value", scale: xScale }, y: valueY };
69
- case "heatmap":
70
- return { x: CATEGORY_AXIS, y: CATEGORY_AXIS };
71
- case "pie":
72
- case "map":
73
- return { x: null, y: null };
74
- default:
75
- throw new Error(`Expected a known plot type to decide its axes; got "${plot.type}".`);
76
- }
77
- }
@@ -1,16 +0,0 @@
1
- /** The field of plots that can draw a marker for each row of data. */
2
-
3
- import { z } from "zod";
4
-
5
- /** Markers when the agent sends none, except on a line coloured by a number. */
6
- export const DEFAULT_SHOW_MARKERS = false;
7
-
8
- /** The field of plots that can mark each row: line and box. */
9
- export const MARKER_FIELDS = {
10
- // No schema default: a line coloured by a number needs its markers to carry
11
- // the colour, so the model tells "not sent" apart from false.
12
- show_markers: z
13
- .boolean()
14
- .optional()
15
- .describe("Draw a marker for each row of data. Default: off, except on a line coloured by a number, whose markers carry the colour."),
16
- };
@@ -1,67 +0,0 @@
1
- /**
2
- * The figure: one shared table and one or more plots in a grid. This is
3
- * the whole shape a caller sends, and the one list of plot types.
4
- */
5
-
6
- import { z } from "zod";
7
- import { BAR_NUMERIC_COLUMNS, BAR_PLOT_SCHEMA } from "../plots/bar_plot";
8
- import { BOX_NUMERIC_COLUMNS, BOX_PLOT_SCHEMA } from "../plots/box_plot";
9
- import { DENSITY_NUMERIC_COLUMNS, DENSITY_PLOT_SCHEMA } from "../plots/density_plot";
10
- import { HEATMAP_NUMERIC_COLUMNS, HEATMAP_PLOT_SCHEMA } from "../plots/heatmap_plot";
11
- import { HISTOGRAM_NUMERIC_COLUMNS, HISTOGRAM_PLOT_SCHEMA } from "../plots/histogram_plot";
12
- import { LINE_NUMERIC_COLUMNS, LINE_PLOT_SCHEMA } from "../plots/line_plot";
13
- import { MAP_NUMERIC_COLUMNS, MAP_PLOT_SCHEMA } from "../plots/map_plot";
14
- import { PIE_NUMERIC_COLUMNS, PIE_PLOT_SCHEMA } from "../plots/pie_plot";
15
- import { SCATTER_NUMERIC_COLUMNS, SCATTER_PLOT_SCHEMA } from "../plots/scatter_plot";
16
- import { DATA_TABLE_SCHEMA } from "../table/data_table";
17
-
18
- /** Every plot type's schema, in the order the catalogue lists them. */
19
- export const PLOT_SCHEMAS = [
20
- LINE_PLOT_SCHEMA, SCATTER_PLOT_SCHEMA, BAR_PLOT_SCHEMA, BOX_PLOT_SCHEMA,
21
- HISTOGRAM_PLOT_SCHEMA, DENSITY_PLOT_SCHEMA, HEATMAP_PLOT_SCHEMA, PIE_PLOT_SCHEMA, MAP_PLOT_SCHEMA,
22
- ] as const;
23
-
24
- /** Any one plot, told apart by its type. */
25
- export const PLOT_SCHEMA = z.discriminatedUnion("type", PLOT_SCHEMAS);
26
-
27
- /** Any one plot, through the schema. */
28
- export type Plot = z.infer<typeof PLOT_SCHEMA>;
29
- /** The name of a plot type. */
30
- export type PlotType = Plot["type"];
31
-
32
- /** Every plot but a map: the plots with x and y. */
33
- export type ChartPlot = Exclude<Plot, { type: "map" }>;
34
-
35
- /** Each plot type's column fields that must hold numbers. */
36
- export const NUMERIC_COLUMNS: Readonly<Record<PlotType, readonly string[]>> = {
37
- line: LINE_NUMERIC_COLUMNS, scatter: SCATTER_NUMERIC_COLUMNS, bar: BAR_NUMERIC_COLUMNS, box: BOX_NUMERIC_COLUMNS,
38
- histogram: HISTOGRAM_NUMERIC_COLUMNS, density: DENSITY_NUMERIC_COLUMNS, heatmap: HEATMAP_NUMERIC_COLUMNS, pie: PIE_NUMERIC_COLUMNS, map: MAP_NUMERIC_COLUMNS,
39
- };
40
-
41
- /** The chart libraries a figure can be drawn with. */
42
- export const RENDERERS = ["plotly", "echarts"] as const;
43
-
44
- /** Whether panels share an axis when the agent does not say: no. */
45
- export const DEFAULT_IS_AXIS_SHARED = false;
46
-
47
- /** The whole figure an agent sends: one table and its plots. Its JSON Schema is what an agent reads. */
48
- export const PLOT_FIGURE_SCHEMA = z.strictObject({
49
- data: DATA_TABLE_SCHEMA.describe("The table the plots draw from, unless a plot brings its own."),
50
- plots: z.array(PLOT_SCHEMA).min(1).describe("The plots, filling the grid row by row."),
51
- grid: z
52
- .strictObject({ rows: z.number().int().min(1), columns: z.number().int().min(1) })
53
- .optional()
54
- .describe("Rows and columns of plots. Default: one column, a row per plot."),
55
- title: z.string().min(1).optional().describe("A title over the whole figure."),
56
- // The host shows the caption under the chart; neither library draws it, so plotilla passes it through.
57
- caption: z.string().min(1).optional().describe("A line the host shows under the figure: its source, or what to notice."),
58
- renderer: z.enum(RENDERERS).optional().describe("The library that draws the figure. Default: the caller's."),
59
- is_x_axis_shared: z.boolean().default(DEFAULT_IS_AXIS_SHARED).describe("Link the x axes of the plots that have one (pies and maps have none), so zooming one zooms all. Needs two or more, of one kind (numbers, categories or dates) and one scale."),
60
- is_y_axis_shared: z.boolean().default(DEFAULT_IS_AXIS_SHARED).describe("Link the y axes of the plots that have one (pies and maps have none), so zooming one zooms all. Needs two or more, of one kind (numbers, categories or dates) and one scale."),
61
- });
62
-
63
- /** A figure through the schema, every default filled in: what the model draws. */
64
- export type PlotFigure = z.output<typeof PLOT_FIGURE_SCHEMA>;
65
-
66
- /** A figure as a caller writes it, defaults left out. */
67
- export type PlotFigureInput = z.input<typeof PLOT_FIGURE_SCHEMA>;
@@ -1,47 +0,0 @@
1
- /**
2
- * Resolve a figure the way a host shows one: check it, load the outlines its
3
- * map layers name, and build its model once so any problem surfaces now
4
- * rather than as a broken chart (renderers build their own).
5
- */
6
-
7
- import { resolveBoundarySet, type BoundarySetLoader } from "../map/boundary_sets";
8
- import { fetchRegionOutlines, type GeoJsonFetcher } from "../map/fetch_region_outlines";
9
- import { computePanelRectangles, type FigureSize } from "../model/panel_layout";
10
- import { buildFigureModel } from "../model/plot_model";
11
- import type { PlotFigure } from "./plot_figure";
12
- import { validatePlotFigure, validatePlotFigureBeforeOutlines, type PlotFigureLimits } from "./validate_plot_figure";
13
-
14
- /** A figure checked and with its outlines loaded, and what the agent should be told about it. */
15
- export type ResolvedPlotFigure = { figure: PlotFigure; notes: string[] };
16
-
17
- /**
18
- * Resolve a figure.
19
- *
20
- * @param input - The figure as the caller sent it. Never changed: outlines go into a copy.
21
- * @param options - The caller's limits, the size it draws at in pixels, how to load a built-in outline set, and how to fetch outlines from an address.
22
- * @returns The figure, valid, defaults and outlines filled in, and notes for the agent (unmatched region names, what a renderer cannot draw).
23
- */
24
- export async function resolvePlotFigure(
25
- input: unknown,
26
- options: { limits: PlotFigureLimits; size: FigureSize; loadBoundarySet: BoundarySetLoader; fetchGeoJson: GeoJsonFetcher },
27
- ): Promise<ResolvedPlotFigure> {
28
- // Everything that needs no outlines first, so a figure that will be refused fetches nothing.
29
- const figure = validatePlotFigureBeforeOutlines(input, { limits: options.limits });
30
- const boundaryNotes: string[] = [];
31
- for (const [index, plot] of figure.plots.entries()) {
32
- if (plot.type !== "map") continue;
33
- for (const [layerIndex, layer] of plot.layers.entries()) {
34
- if (layer.type !== "regions" || layer.boundaries === undefined) continue;
35
- const note = await resolveBoundarySet(layer, {
36
- table: layer.data ?? plot.data ?? figure.data, where: `plots[${index}].layers[${layerIndex}]`, loadBoundarySet: options.loadBoundarySet,
37
- });
38
- if (note !== null) boundaryNotes.push(note);
39
- }
40
- await fetchRegionOutlines(plot.layers, { where: `plots[${index}]`, fetchGeoJson: options.fetchGeoJson });
41
- }
42
- const resolved = validatePlotFigure(figure, { limits: options.limits });
43
- const model = buildFigureModel(resolved);
44
- // Laid out once at the host's size, so a figure that cannot fit is refused now, not when drawn.
45
- computePanelRectangles(model, { size: options.size });
46
- return { figure: resolved, notes: [...boundaryNotes, ...model.notes] };
47
- }