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,171 +0,0 @@
1
- /**
2
- * Where each plot of a figure sits: the header (title and legend) at the top,
3
- * then the panels in their grid. Shared by both renderers, so ECharts and
4
- * Plotly lay a figure out the same way.
5
- *
6
- * Every gap is sized in pixels from what it must hold (tick labels, axis
7
- * titles, legend rows, colour scales), using the figure's size in pixels from
8
- * the host, so a small figure never draws one panel's labels over another's.
9
- */
10
-
11
- import { formatValue } from "../colour/colour_scale";
12
- import { getNumberRange } from "../table/get_number_range";
13
- import type { FigureModel, PanelModel } from "./panel_model";
14
-
15
- /** How wide one tick label character is drawn, in pixels: tick fonts are about 11-12 px. */
16
- export const AXIS_LABEL_CHARACTER_PIXELS = 7;
17
-
18
- /** An axis title's line plus its clearance from the tick labels, in pixels. */
19
- export const AXIS_TITLE_ROOM_PIXELS = 24;
20
-
21
- /** A legend appears from two series up; one series is named by the title (dataviz skill). */
22
- export const MINIMUM_SERIES_FOR_LEGEND = 2;
23
-
24
- /** The figure's size in pixels, as the host draws it. */
25
- export type FigureSize = { width: number; height: number };
26
-
27
- /** Where a panel sits, as fractions of the figure measured from the top left. */
28
- export type PanelRectangle = { left: number; top: number; width: number; height: number };
29
-
30
- /** Space kept at the figure's edges, in pixels. */
31
- const EDGE_PADDING_PIXELS = 12;
32
- /** Space between one panel's furniture and the next panel's, in pixels. */
33
- const PANEL_SPACING_PIXELS = 12;
34
- /** One line of x tick labels, in pixels. */
35
- const X_TICK_LABEL_LINE_PIXELS = 18;
36
- /** The figure's title line, in pixels. */
37
- const FIGURE_TITLE_ROOM_PIXELS = 30;
38
- /** One row of legend entries, in pixels. */
39
- const LEGEND_ROW_PIXELS = 24;
40
- /** A legend entry's symbol and the gaps around it, in pixels; its name adds a character width per character. */
41
- const LEGEND_ENTRY_EXTRA_PIXELS = 40;
42
- const LEGEND_CHARACTER_PIXELS = 7;
43
- /** A panel's own title line, in pixels. */
44
- const PANEL_TITLE_ROOM_PIXELS = 22;
45
- /** A colour scale's bar and the gaps either side of it, in pixels; its labels add a character width per character. */
46
- const COLOUR_SCALE_BAR_ROOM_PIXELS = 40;
47
- /** The smallest panel worth drawing, in pixels. */
48
- const MINIMUM_PANEL_PIXELS = { width: 80, height: 40 };
49
-
50
- /** What a panel needs around it, in pixels. */
51
- type PanelRoom = { left: number; right: number; bottom: number; top: number };
52
-
53
- /**
54
- * Measure what a panel needs around it: tick labels and titles of its axes,
55
- * its own title, and a colour scale beside it.
56
- *
57
- * @param panel - The panel.
58
- * @returns Its room on each side, in pixels.
59
- */
60
- function measurePanelRoom(panel: PanelModel): PanelRoom {
61
- return {
62
- left: panel.yAxis === null ? 0 : panel.yAxis.longestLabelCharacters * AXIS_LABEL_CHARACTER_PIXELS + AXIS_TITLE_ROOM_PIXELS,
63
- right: panel.colourScale === null ? 0 : COLOUR_SCALE_BAR_ROOM_PIXELS + measureColourScaleLabelCharacters(panel.colourScale) * AXIS_LABEL_CHARACTER_PIXELS,
64
- bottom: panel.xAxis === null ? 0 : X_TICK_LABEL_LINE_PIXELS + AXIS_TITLE_ROOM_PIXELS,
65
- top: panel.title === null ? 0 : PANEL_TITLE_ROOM_PIXELS,
66
- };
67
- }
68
-
69
- /**
70
- * The widest label a colour scale prints, in characters: its title, its
71
- * ticks, and its ends (a linear scale's own ticks are numbers like these).
72
- *
73
- * @param scale - The panel's colour scale.
74
- * @returns The widest label's length.
75
- */
76
- function measureColourScaleLabelCharacters(scale: NonNullable<PanelModel["colourScale"]>): number {
77
- const labels = [scale.label, formatValue(scale.minimum), formatValue(scale.maximum), ...(scale.ticks ?? []).map((tick) => tick.text)];
78
- return findLargest(labels.map((label) => label.length));
79
- }
80
-
81
- /**
82
- * Count the legend's rows at this width: entries are packed left to right
83
- * and wrap, as both libraries draw a horizontal legend.
84
- *
85
- * @param names - The legend's entries.
86
- * @param options - The width available, in pixels.
87
- * @returns The number of rows.
88
- */
89
- function countLegendRows(names: readonly string[], options: { width: number }): number {
90
- let rows = 1;
91
- let used = 0;
92
- for (const name of names) {
93
- const entry = LEGEND_ENTRY_EXTRA_PIXELS + name.length * LEGEND_CHARACTER_PIXELS;
94
- if (used > 0 && used + entry > options.width) {
95
- rows += 1;
96
- used = 0;
97
- }
98
- used += entry;
99
- }
100
- return rows;
101
- }
102
-
103
- /**
104
- * The largest of some numbers, or 0 when there are none.
105
- *
106
- * @param values - The numbers.
107
- * @returns The largest.
108
- */
109
- function findLargest(values: readonly number[]): number {
110
- return Math.max(0, getNumberRange(values).maximum);
111
- }
112
-
113
- /**
114
- * Place each panel in the grid, row by row.
115
- *
116
- * @param model - The figure.
117
- * @param options - The figure's size in pixels, from the host.
118
- * @returns One rectangle per panel, in panel order.
119
- */
120
- export function computePanelRectangles(model: FigureModel, options: { size: FigureSize }): PanelRectangle[] {
121
- const { size } = options;
122
- const rooms = model.panels.map(measurePanelRoom);
123
- const roomsInColumn = (column: number): PanelRoom[] => rooms.filter((_, index) => index % model.columns === column);
124
- const roomsInRow = (row: number): PanelRoom[] => rooms.filter((_, index) => Math.floor(index / model.columns) === row);
125
-
126
- const hasLegend = model.legendNames.length >= MINIMUM_SERIES_FOR_LEGEND;
127
- const legendRows = hasLegend ? countLegendRows(model.legendNames, { width: size.width - 2 * EDGE_PADDING_PIXELS }) : 0;
128
- const header = EDGE_PADDING_PIXELS + (model.title === null ? 0 : FIGURE_TITLE_ROOM_PIXELS) + legendRows * LEGEND_ROW_PIXELS;
129
-
130
- // Each column starts after its widest left room; each gap also holds the previous column's right room.
131
- const columnStarts: number[] = [];
132
- let x = EDGE_PADDING_PIXELS;
133
- for (let column = 0; column < model.columns; column += 1) {
134
- if (column > 0) x += findLargest(roomsInColumn(column - 1).map((room) => room.right)) + PANEL_SPACING_PIXELS;
135
- x += findLargest(roomsInColumn(column).map((room) => room.left));
136
- columnStarts.push(x);
137
- }
138
- const lastRight = findLargest(roomsInColumn(model.columns - 1).map((room) => room.right));
139
- const furnitureWidth = x + lastRight + EDGE_PADDING_PIXELS;
140
-
141
- const rowStarts: number[] = [];
142
- let y = header;
143
- for (let row = 0; row < model.rows; row += 1) {
144
- // A panel title's own room already separates it from the row above; spacing stands in when there is none.
145
- const titleRoom = findLargest(roomsInRow(row).map((room) => room.top));
146
- if (row > 0) y += findLargest(roomsInRow(row - 1).map((room) => room.bottom)) + Math.max(titleRoom, PANEL_SPACING_PIXELS);
147
- else y += titleRoom;
148
- rowStarts.push(y);
149
- }
150
- const lastBottom = findLargest(roomsInRow(model.rows - 1).map((room) => room.bottom));
151
- const furnitureHeight = y + lastBottom + EDGE_PADDING_PIXELS;
152
-
153
- const panelWidth = (size.width - furnitureWidth) / model.columns;
154
- const panelHeight = (size.height - furnitureHeight) / model.rows;
155
- if (panelWidth < MINIMUM_PANEL_PIXELS.width || panelHeight < MINIMUM_PANEL_PIXELS.height) {
156
- const neededWidth = Math.ceil(furnitureWidth + model.columns * MINIMUM_PANEL_PIXELS.width);
157
- const neededHeight = Math.ceil(furnitureHeight + model.rows * MINIMUM_PANEL_PIXELS.height);
158
- throw new Error(
159
- `The figure needs at least ${Math.max(neededWidth, size.width)} x ${Math.max(neededHeight, size.height)} pixels `
160
- + `for its labels, legend and ${model.panels.length} plot${model.panels.length === 1 ? "" : "s"}; got ${size.width} x ${size.height}.`,
161
- );
162
- }
163
-
164
- return model.panels.map((_, index) => {
165
- const row = Math.floor(index / model.columns);
166
- const column = index % model.columns;
167
- const left = (columnStarts[column] ?? 0) + column * panelWidth;
168
- const top = (rowStarts[row] ?? 0) + row * panelHeight;
169
- return { left: left / size.width, top: top / size.height, width: panelWidth / size.width, height: panelHeight / size.height };
170
- });
171
- }
@@ -1,85 +0,0 @@
1
- /**
2
- * The renderer-neutral model's types: what a figure, a panel, a series, an
3
- * axis and a map are once every decision is made. Kept apart from the code
4
- * that builds them, so the chart model and the map model both use them
5
- * without importing each other.
6
- */
7
-
8
- import type { LineDash, MarkerShape, PlotTheme } from "../colour/palette";
9
- import type { AxisScale } from "../fields/axis_fields";
10
- import type { AxisKind } from "../fields/decide_plot_axes";
11
- import type { Bounds, FeatureCollection } from "../map/geojson";
12
- import type { MapProjection } from "../plots/map_plot";
13
- import type { BoxSummary, HistogramBin } from "./statistics";
14
-
15
- /** A value along an axis: a number, or a category's text. */
16
- export type Value = number | string;
17
-
18
- /**
19
- * `includesZero`: bars, histograms and densities measure from zero, so their value axis must show it.
20
- * `longestLabelCharacters`: an estimate of the widest tick label, so a renderer can place the axis title clear of it.
21
- */
22
- export type AxisModel = {
23
- kind: AxisKind; label: string; scale: AxisScale; categories: string[];
24
- includesZero: boolean; longestLabelCharacters: number;
25
- /** Years (2005, not 2,005), decided by `checkAxisShowsYears`: printed without thousands separators. */
26
- isYearLike: boolean;
27
- };
28
-
29
- /** One series of marks, renderer-neutral: what is drawn, in which colour, at which values. */
30
- export type SeriesModel =
31
- /** `colour` is null when a number colours the line along its length (`colourValue` per point). */
32
- | { mark: "line"; name: string; colour: string | null; dash: LineDash; showMarkers: boolean; isFilled: boolean; points: { x: Value; y: number; colourValue: number | null }[] }
33
- | { mark: "scatter"; name: string; colour: string | null; shape: MarkerShape; points: { x: Value; y: number; sizePixels: number; colourValue: number | null }[] }
34
- | { mark: "bar"; name: string; colour: string | null; isStacked: boolean; isHorizontal: boolean; points: { x: string; y: number; colourValue: number | null }[] }
35
- | { mark: "box"; name: string; colour: string; showMarkers: boolean; boxes: { category: string; summary: BoxSummary; values: number[] }[] }
36
- | { mark: "histogram"; name: string; colour: string; bins: HistogramBin[] }
37
- | { mark: "heatmap"; name: string; cells: { x: string; y: string; value: number; colourValue: number | null }[] }
38
- | { mark: "pie"; name: string; hole: number; slices: { label: string; value: number; colour: string }[] };
39
-
40
- /** One panel of the grid: its title, axes, series, colour scale and, for a map, the map. */
41
- export type PanelModel = {
42
- title: string | null;
43
- xAxis: AxisModel | null;
44
- yAxis: AxisModel | null;
45
- series: SeriesModel[];
46
- /** Present when colour encodes a number: the range and the ramp. */
47
- /** `ticks`: legend labels in real values, for scales that transform them (log, quantile maps). */
48
- colourScale: { label: string; minimum: number; maximum: number; colours: readonly string[]; ticks?: { value: number; text: string }[] } | null;
49
- /** Present for a map plot: its layers and view. Maps have no axes or series. */
50
- map?: MapModel;
51
- };
52
-
53
- /** `legendNames`: every series name, once, in first-seen order; a legend shows from two up. */
54
- /** `notes`: things the agent should know about the figure (e.g. map regions with no data). */
55
- export type FigureModel = {
56
- title: string | null; rows: number; columns: number; isXAxisShared: boolean; isYAxisShared: boolean; theme: PlotTheme;
57
- legendNames: string[]; notes: string[]; panels: PanelModel[];
58
- };
59
-
60
- /** A point the model places: where it is, its label, its size in pixels (the marker size with no size column) and colour value. */
61
- export type MapPoint = { longitude: number; latitude: number; label: string | null; sizePixels: number; colourValue: number | null };
62
-
63
- /** A map layer with every colour, join and position decided. */
64
- export type MapLayerModel =
65
- /** `colour` is null when a number colours the points (the panel's colour scale). */
66
- | { kind: "points"; name: string; colour: string | null; isCategory: boolean; points: MapPoint[] }
67
- | { kind: "density"; name: string; points: { longitude: number; latitude: number; weight: number }[] }
68
- /** Regions carry their own colour when coloured by category; `value` drives the colour scale otherwise. */
69
- | { kind: "regions"; name: string; geojson: FeatureCollection; regions: { id: string; value: number | null; colour: string | null; label: string }[] }
70
- | { kind: "lines"; name: string; colour: string | null; isCategory: boolean; lines: { path: [number, number][]; widthPixels: number; colourValue: number | null; label: string | null }[] };
71
-
72
- /** A map panel: its layers, projection, starting view and notes for the agent. */
73
- export type MapModel = {
74
- projection: MapProjection;
75
- /** Where the view starts: [longitude, latitude] and a zoom from 0 (world) up. */
76
- centre: [number, number];
77
- zoom: number;
78
- /** True when the agent set the zoom; a globe then starts that close, else it starts whole. */
79
- isZoomGiven: boolean;
80
- /** Everything shown, for renderers that fit a view to bounds. */
81
- bounds: Bounds | null;
82
- layers: MapLayerModel[];
83
- /** Things the agent should know, e.g. regions with no data. */
84
- notes: string[];
85
- };
@@ -1,347 +0,0 @@
1
- /**
2
- * The renderer-neutral chart model: a validated spec turned into panels of
3
- * ready-to-draw series, with every grouping, colour and statistic decided.
4
- * The ECharts and Plotly mappers only translate this; they decide nothing,
5
- * so the renderer switch never changes what the chart says.
6
- */
7
-
8
- import {
9
- ALL_PAIRS_COLOUR_LIMIT,
10
- pickCategoricalColour,
11
- pickLineDash,
12
- pickMarkerShape,
13
- DEFAULT_PLOT_THEME,
14
- MARKER_SIZE,
15
- PLOT_THEMES,
16
- scaleToPixels,
17
- SEQUENTIAL_COLOURS,
18
- SIZE_RANGE_PIXELS,
19
- type PlotTheme,
20
- } from "../colour/palette";
21
- import { applyColourScale, decideColourIsContinuous } from "../colour/colour_scale";
22
- import { DEFAULT_COLOUR_SCALE, type ColourScale } from "../fields/colour_fields";
23
- import { DEFAULT_SHOW_MARKERS } from "../fields/marker_fields";
24
- import { buildMapPanel } from "./map_model";
25
- import { checkAxisShowsYears } from "./check_axis_shows_years";
26
- import type { AxisModel, FigureModel, PanelModel, SeriesModel, Value } from "./panel_model";
27
- import { decidePlotAxes, type PlotAxis } from "../fields/decide_plot_axes";
28
- import type { Plot, PlotFigure } from "../figure/plot_figure";
29
- import { checkRowBecomesMark, findColumn, findOptionalColumn, type DataTable } from "../table/data_table";
30
- import { groupRows } from "../table/group_rows";
31
- import { listCategories } from "../table/list_categories";
32
- import { listMarkColumns } from "../fields/column_fields";
33
- import { binValues, chooseBinCount, estimateDensity, fitLine, summariseBox } from "./statistics";
34
- import { getNumberRange } from "../table/get_number_range";
35
- import { computeDensityRange, computeSilvermanBandwidth } from "../table/density_bandwidth";
36
-
37
- /** A date tick label (e.g. 2025-01-01) is about this many characters. */
38
- const TIME_LABEL_CHARACTERS = 10;
39
- /** When nothing is known about an axis's values, assume labels this long. */
40
- const DEFAULT_LABEL_CHARACTERS = 4;
41
-
42
- /**
43
- * Estimate the widest tick label for numbers on an axis: ticks are round
44
- * numbers written with thousands separators (2,600,000), or a few decimals
45
- * below 1 (0.025). One extra character covers ticks just past the data.
46
- *
47
- * @param numbers - The values the axis must show.
48
- * @returns An estimated character count.
49
- */
50
- export function estimateNumberLabelCharacters(numbers: number[]): number {
51
- if (numbers.length === 0) return DEFAULT_LABEL_CHARACTERS;
52
- const range = getNumberRange(numbers);
53
- const largest = Math.max(Math.abs(range.minimum), Math.abs(range.maximum));
54
- const sign = numbers.some((value) => value < 0) ? 1 : 0;
55
- if (largest === 0) return 1 + sign;
56
- const digits = largest >= 1
57
- ? Math.round(largest).toLocaleString("en-US").length
58
- : "0.".length + Math.ceil(-Math.log10(largest)) + 1;
59
- return digits + sign + 1;
60
- }
61
-
62
- function buildAxis(options: { values: (number | string | null)[]; column: string | null; label: string; axis: PlotAxis; includesZero?: boolean }): AxisModel {
63
- const { kind, scale } = options.axis;
64
- const categories = kind === "category" ? listCategories(options.values) : [];
65
- const numbers = options.values.filter((value): value is number => typeof value === "number" && Number.isFinite(value));
66
- const longestLabelCharacters = kind === "category"
67
- ? Math.max(0, getNumberRange(categories.map((category) => category.length)).maximum)
68
- : kind === "time" ? TIME_LABEL_CHARACTERS : estimateNumberLabelCharacters(numbers);
69
- const isYearLike = kind === "value" && checkAxisShowsYears({ column: options.column, numbers });
70
- return {
71
- kind, label: options.label, scale, categories,
72
- includesZero: options.includesZero ?? false, longestLabelCharacters, isYearLike,
73
- };
74
- }
75
-
76
-
77
- /**
78
- * Read a column at the given rows only, in their order.
79
- *
80
- * @param values - The column.
81
- * @param options - The rows to read (groupRows' drawnRows, so an axis sees only rows drawn).
82
- * @returns The values at those rows.
83
- */
84
- function pickRows<T>(values: T[], options: { rows: number[] }): (T | null)[] {
85
- return options.rows.map((row) => values[row] ?? null);
86
- }
87
-
88
- function readNumber(value: number | string | null | undefined): number | null {
89
- return typeof value === "number" && Number.isFinite(value) ? value : null;
90
- }
91
-
92
- /**
93
- * Turn a column's numbers into what colour follows, per colour_scale, and the
94
- * legend that goes with it: real values at its ends and ticks.
95
- *
96
- * @param values - The numbers (null where missing).
97
- * @param options - The plot's colour_scale, the column's name, and where to put notes for the agent.
98
- * @returns The value each mark is coloured by, and the panel's colour scale.
99
- */
100
- function buildColourScale(
101
- values: (number | null)[],
102
- options: { scale: ColourScale; label: string; notes: string[] },
103
- ): { colourValues: (number | null)[]; colourScale: NonNullable<PanelModel["colourScale"]> } {
104
- const transformed = applyColourScale(values, { scale: options.scale, label: options.label, notes: options.notes });
105
- const present = transformed.values.filter((value): value is number => value !== null);
106
- return {
107
- colourValues: transformed.values,
108
- colourScale: {
109
- label: options.label, ...getNumberRange(present), colours: SEQUENTIAL_COLOURS,
110
- ...(transformed.ticks === undefined ? {} : { ticks: transformed.ticks }),
111
- },
112
- };
113
- }
114
-
115
- function buildPanel(plot: Plot, options: { table: DataTable; theme: PlotTheme; notes: string[] }): PanelModel {
116
- const { table, theme } = options;
117
- if (plot.type === "map") return buildMapPanel(plot, { table, theme });
118
- const firstColumn = Object.values(table)[0] ?? [];
119
- const rowCount = firstColumn.length;
120
- const colour = "colour" in plot ? plot.colour : undefined;
121
- const colourValues = findOptionalColumn(table, { column: colour });
122
- const colourType = "colour_type" in plot ? plot.colour_type : undefined;
123
- const isContinuous = colourValues !== null && decideColourIsContinuous(colourValues, { colourType });
124
- // One rule for which rows become marks, shared with validation: only they set a range or make a series.
125
- const markColumns = listMarkColumns(plot, { isColourCategorical: colourValues !== null && !isContinuous });
126
- const isDrawn = (row: number): boolean => checkRowBecomesMark(table, { row, ...markColumns });
127
- const scaled = isContinuous && colourValues !== null && (plot.type === "line" || plot.type === "scatter" || plot.type === "bar")
128
- ? buildColourScale(colourValues.map((value, row) => (isDrawn(row) ? readNumber(value) : null)), {
129
- scale: plot.colour_scale ?? DEFAULT_COLOUR_SCALE, label: colour ?? "", notes: options.notes,
130
- })
131
- : null;
132
- const continuousColours = scaled === null ? null : scaled.colourValues;
133
- const colourScale = scaled === null ? null : scaled.colourScale;
134
- const title = plot.title ?? null;
135
- // One rule for each axis's kind and scale, shared with validation, which judges shared axes by it.
136
- const axes = decidePlotAxes(plot, { table });
137
- const requireAxis = (axis: PlotAxis | null): PlotAxis => {
138
- if (axis === null) throw new Error(`Expected a ${plot.type} plot to have both axes.`);
139
- return axis;
140
- };
141
-
142
- switch (plot.type) {
143
- case "line":
144
- case "scatter": {
145
- const xValues = findColumn(table, { column: plot.x }) as (number | string | null)[];
146
- const yValues = findColumn(table, { column: plot.y }) as (number | null)[];
147
- const style = plot.type === "line" ? plot.line_type : plot.marker_shape;
148
- const { grouping, groups, drawnRows } = groupRows(table, { rowCount, colour: isContinuous ? undefined : plot.colour, style, isDrawn });
149
- const xAxis = buildAxis({ values: pickRows(xValues, { rows: drawnRows }), column: plot.x, label: plot.x_label ?? plot.x, axis: requireAxis(axes.x) });
150
- const yAxis = buildAxis({ values: pickRows(yValues, { rows: drawnRows }), column: plot.y, label: plot.y_label ?? plot.y, axis: requireAxis(axes.y) });
151
- // Sizes scale once over every drawn row, across groups, so one value is one size in the whole plot.
152
- const sizeValues = plot.type === "scatter" ? findOptionalColumn(table, { column: plot.size }) : null;
153
- const sizePixels = sizeValues === null ? null : scaleToPixels(sizeValues.map((value, row) => (isDrawn(row) ? readNumber(value) : null)), { range: SIZE_RANGE_PIXELS, fallback: MARKER_SIZE });
154
- const series: SeriesModel[] = [];
155
- for (const group of groups) {
156
- const colour = isContinuous ? null : pickCategoricalColour(group.colourIndex, { theme });
157
- const { rows } = group;
158
- if (plot.type === "line") {
159
- series.push({
160
- mark: "line", name: group.name, colour, dash: pickLineDash(style === undefined ? 0 : group.styleIndex),
161
- // Coloured by a number, the points show the colour where a renderer cannot shade the line itself.
162
- showMarkers: plot.show_markers ?? isContinuous, isFilled: false,
163
- points: rows.map((row) => ({
164
- x: xValues[row] as Value, y: yValues[row] as number,
165
- colourValue: continuousColours === null ? null : (continuousColours[row] ?? null),
166
- })),
167
- });
168
- continue;
169
- }
170
- // Past the all-pairs limit, shape carries identity alongside colour.
171
- const shapeIndex = style !== undefined ? group.styleIndex
172
- : grouping.colourCategories.length > ALL_PAIRS_COLOUR_LIMIT ? group.colourIndex : 0;
173
- series.push({
174
- mark: "scatter", name: group.name, colour, shape: pickMarkerShape(shapeIndex),
175
- points: rows.map((row) => ({
176
- x: xValues[row] as Value, y: yValues[row] as number,
177
- sizePixels: sizePixels === null ? MARKER_SIZE : (sizePixels[row] ?? MARKER_SIZE),
178
- colourValue: continuousColours === null ? null : (continuousColours[row] ?? null),
179
- })),
180
- });
181
- if (plot.show_trend_line && xAxis.kind === "value") {
182
- const points = rows.map((row) => ({ x: xValues[row] as number, y: yValues[row] as number }));
183
- const { start, end } = fitLine(points);
184
- series.push({
185
- mark: "line", name: `${group.name || plot.y} trend`, colour: colour ?? PLOT_THEMES[theme].textSecondary, dash: "dashed",
186
- showMarkers: false, isFilled: false, points: [{ ...start, colourValue: null }, { ...end, colourValue: null }],
187
- });
188
- }
189
- }
190
- return { title, xAxis, yAxis, series, colourScale };
191
- }
192
- case "bar": {
193
- const xValues = findColumn(table, { column: plot.x }) as (number | string | null)[];
194
- const yValues = findColumn(table, { column: plot.y }) as (number | null)[];
195
- const { groups, drawnRows } = groupRows(table, { rowCount, colour: isContinuous ? undefined : plot.colour, style: undefined, isDrawn });
196
- const isHorizontal = plot.orientation === "horizontal";
197
- // The x column holds the categories and y the values, whichever way the bars lie.
198
- const categoryAxis = buildAxis({ values: pickRows(xValues, { rows: drawnRows }), column: plot.x, label: plot.x_label ?? plot.x, axis: requireAxis(isHorizontal ? axes.y : axes.x) });
199
- const valueAxis = buildAxis({ values: pickRows(yValues, { rows: drawnRows }), column: plot.y, label: plot.y_label ?? plot.y, axis: requireAxis(isHorizontal ? axes.x : axes.y), includesZero: true });
200
- const series: SeriesModel[] = groups.map((group) => ({
201
- mark: "bar", name: group.name, colour: isContinuous ? null : pickCategoricalColour(group.colourIndex, { theme }),
202
- isStacked: plot.mode === "stacked", isHorizontal,
203
- points: group.rows.map((row) => ({
204
- x: String(xValues[row]), y: yValues[row] as number,
205
- colourValue: continuousColours === null ? null : (continuousColours[row] ?? null),
206
- })),
207
- }));
208
- if (plot.mode === "stacked") {
209
- // Stacked bars reach the sum of each category, not its largest part.
210
- const totals = new Map<string, number>();
211
- for (const entry of series) if (entry.mark === "bar") for (const point of entry.points) totals.set(point.x, (totals.get(point.x) ?? 0) + point.y);
212
- valueAxis.longestLabelCharacters = estimateNumberLabelCharacters([...totals.values()]);
213
- }
214
- return { title, xAxis: isHorizontal ? valueAxis : categoryAxis, yAxis: isHorizontal ? categoryAxis : valueAxis, series, colourScale };
215
- }
216
- case "box": {
217
- const yValues = findColumn(table, { column: plot.y }) as (number | null)[];
218
- const xValues = findOptionalColumn(table, { column: plot.x });
219
- const { groups, drawnRows } = groupRows(table, { rowCount, colour: plot.colour, style: undefined, isDrawn });
220
- const categories = xValues === null ? [plot.y] : listCategories(pickRows(xValues, { rows: drawnRows }));
221
- // Each group's rows are split by category in one pass, so the work is linear in rows, not rows times categories.
222
- const rowsByCategory = new Map(groups.map((group) => {
223
- const rowsOfCategory = new Map<string, number[]>();
224
- for (const row of group.rows) {
225
- const category = xValues === null ? plot.y : xValues[row] === null ? null : String(xValues[row]);
226
- if (category === null) continue;
227
- const rows = rowsOfCategory.get(category);
228
- if (rows === undefined) rowsOfCategory.set(category, [row]); else rows.push(row);
229
- }
230
- return [group, rowsOfCategory] as const;
231
- }));
232
- const series: SeriesModel[] = groups.map((group) => ({
233
- mark: "box", name: group.name, colour: pickCategoricalColour(group.colourIndex, { theme }), showMarkers: plot.show_markers ?? DEFAULT_SHOW_MARKERS,
234
- boxes: categories.flatMap((category) => {
235
- const values = (rowsByCategory.get(group)?.get(category) ?? []).map((row) => readNumber(yValues[row])).filter((value): value is number => value !== null);
236
- return values.length === 0 ? [] : [{ category, summary: summariseBox(values), values }];
237
- }),
238
- }));
239
- const xAxis: AxisModel = {
240
- ...requireAxis(axes.x), label: plot.x_label ?? plot.x ?? "", categories, includesZero: false, isYearLike: false,
241
- longestLabelCharacters: Math.max(0, getNumberRange(categories.map((category) => category.length)).maximum),
242
- };
243
- const yAxis = buildAxis({ values: pickRows(yValues, { rows: drawnRows }), column: plot.y, label: plot.y_label ?? plot.y, axis: requireAxis(axes.y) });
244
- return { title, xAxis, yAxis, series, colourScale: null };
245
- }
246
- case "histogram":
247
- case "density": {
248
- const xValues = (findColumn(table, { column: plot.x }) as (number | null)[]);
249
- const { groups, drawnRows } = groupRows(table, { rowCount, colour: plot.colour, style: undefined, isDrawn });
250
- const drawnValues = pickRows(xValues, { rows: drawnRows });
251
- const drawnNumbers = drawnValues.map(readNumber).filter((value): value is number => value !== null);
252
- if (drawnNumbers.length === 0) throw new Error(`Expected a drawn row with a number in "${plot.x}"; validation refuses a figure without one.`);
253
- const xAxis = buildAxis({ values: drawnValues, column: plot.x, label: plot.x_label ?? plot.x, axis: requireAxis(axes.x) });
254
- const yLabel = plot.type === "density" || (plot.type === "histogram" && plot.is_normalised) ? "density" : "count";
255
- const yAxis = buildAxis({ values: [], column: null, label: plot.y_label ?? yLabel, axis: requireAxis(axes.y), includesZero: true });
256
- const { minimum, maximum } = getNumberRange(drawnNumbers);
257
- const series: SeriesModel[] = groups.map((group) => {
258
- const values = group.rows.map((row) => readNumber(xValues[row])).filter((value): value is number => value !== null);
259
- const colour = pickCategoricalColour(group.colourIndex, { theme });
260
- if (plot.type === "histogram") {
261
- const binCount = plot.bins ?? chooseBinCount(drawnNumbers.length);
262
- return { mark: "histogram", name: group.name, colour, bins: binValues(values, { binCount, minimum, maximum, isNormalised: plot.is_normalised }) };
263
- }
264
- const bandwidth = plot.bandwidth ?? computeSilvermanBandwidth(values);
265
- const range = computeDensityRange({ minimum, maximum, bandwidth });
266
- const points = estimateDensity(values, { bandwidth, minimum: range.minimum, maximum: range.maximum }).map((point) => ({ ...point, colourValue: null }));
267
- return { mark: "line", name: group.name, colour, dash: "solid", showMarkers: false, isFilled: plot.show_area, points };
268
- });
269
- // The y values (counts, densities) exist only now.
270
- yAxis.longestLabelCharacters = estimateNumberLabelCharacters(series.flatMap((entry) =>
271
- entry.mark === "histogram" ? entry.bins.map((bin) => bin.height) : entry.mark === "line" ? entry.points.map((point) => point.y) : []));
272
- return { title, xAxis, yAxis, series, colourScale: null };
273
- }
274
- case "heatmap": {
275
- const xValues = findColumn(table, { column: plot.x }) as (number | string | null)[];
276
- const yValues = findColumn(table, { column: plot.y }) as (number | string | null)[];
277
- const cellValues = findColumn(table, { column: plot.value }) as (number | null)[];
278
- const placed = xValues.flatMap((x, row) => {
279
- const value = readNumber(cellValues[row]);
280
- return x === null || yValues[row] === null || yValues[row] === undefined || value === null ? [] : [{ x: String(x), y: String(yValues[row]), value }];
281
- });
282
- const { colourValues: cellColours, colourScale: heatmapScale } = buildColourScale(
283
- placed.map((cell) => cell.value), { scale: plot.colour_scale ?? DEFAULT_COLOUR_SCALE, label: plot.value, notes: options.notes },
284
- );
285
- const cells = placed.map((cell, index) => ({ ...cell, colourValue: cellColours[index] ?? null }));
286
- return {
287
- title,
288
- xAxis: buildAxis({ values: xValues, column: plot.x, label: plot.x_label ?? plot.x, axis: requireAxis(axes.x) }),
289
- yAxis: buildAxis({ values: yValues, column: plot.y, label: plot.y_label ?? plot.y, axis: requireAxis(axes.y) }),
290
- series: [{ mark: "heatmap", name: plot.value, cells }],
291
- colourScale: heatmapScale,
292
- };
293
- }
294
- case "pie": {
295
- const labels = findColumn(table, { column: plot.label }) as (number | string | null)[];
296
- const values = findColumn(table, { column: plot.value }) as (number | null)[];
297
- const slices = labels.flatMap((label, row) => {
298
- const value = readNumber(values[row]);
299
- return label === null || value === null ? [] : [{ label: String(label), value }];
300
- });
301
- return {
302
- title, xAxis: null, yAxis: null, colourScale: null,
303
- series: [{ mark: "pie", name: plot.value, hole: plot.hole, slices: slices.map((slice, index) => ({ ...slice, colour: pickCategoricalColour(index, { theme }) })) }],
304
- };
305
- }
306
- }
307
- }
308
-
309
- /**
310
- * Build the chart model for a validated figure.
311
- *
312
- * @param figure - A figure that passed validatePlotFigure.
313
- * @param options - The theme it is drawn in (default: dark).
314
- * @returns Panels in grid order (row by row), ready for a renderer.
315
- */
316
- export function buildFigureModel(figure: PlotFigure, options: { theme?: PlotTheme } = {}): FigureModel {
317
- const theme = options.theme ?? DEFAULT_PLOT_THEME;
318
- const rows = figure.grid?.rows ?? figure.plots.length;
319
- const columns = figure.grid?.columns ?? 1;
320
- const chartNotes: string[] = [];
321
- const panels = figure.plots.map((plot) => buildPanel(plot, { table: plot.data ?? figure.data, theme, notes: chartNotes }));
322
- const legendNames = [...new Set(panels.flatMap((panel) => [
323
- ...panel.series.map((series) => series.name),
324
- // Map layers join the legend when they are colour categories.
325
- ...(panel.map?.layers ?? []).flatMap((layer) => ((layer.kind === "points" || layer.kind === "lines") && layer.isCategory ? [layer.name] : [])),
326
- ]).filter((name) => name !== ""))];
327
- const notes = [...chartNotes, ...panels.flatMap((panel) => panel.map?.notes ?? [])];
328
- // One plot needs one title: keep the figure's, or move the plot's up to
329
- // the top. Plot titles only tell plots apart in a grid.
330
- let title = figure.title ?? null;
331
- const onlyPanel = panels.length === 1 ? panels[0] : undefined;
332
- if (onlyPanel !== undefined) {
333
- title = title ?? onlyPanel.title;
334
- onlyPanel.title = null;
335
- }
336
- return {
337
- title,
338
- rows,
339
- columns,
340
- isXAxisShared: figure.is_x_axis_shared,
341
- isYAxisShared: figure.is_y_axis_shared,
342
- theme,
343
- legendNames,
344
- notes,
345
- panels,
346
- };
347
- }