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,317 +0,0 @@
1
- /**
2
- * Chart model → ECharts option object. Plain JSON (no functions), so it can
3
- * be sent to the page as-is and passed to `chart.setOption`.
4
- */
5
-
6
- import { buildColourLegendText } from "../colour/colour_scale";
7
- import { LINE_WIDTH, MARKER_SIZE, SEQUENTIAL_COLOURS, PLOT_THEMES, type LineDash, type MarkerShape, type PlotTheme } from "../colour/palette";
8
- import { buildEChartsMap, type EChartsMapParts } from "./echarts_map";
9
- import type { AxisModel, FigureModel, PanelModel, SeriesModel } from "../model/panel_model";
10
- import { AXIS_LABEL_CHARACTER_PIXELS, computePanelRectangles, MINIMUM_SERIES_FOR_LEGEND, type FigureSize } from "../model/panel_layout";
11
-
12
- const PERCENT = 100;
13
- /** ECharts dash for "dash_dot": 8px dash, 4px gap, 2px dot, 4px gap. */
14
- const DASH_DOT_PATTERN = [8, 4, 2, 4];
15
- const FILLED_AREA_OPACITY = 0.25;
16
- /** Rounded data ends, per the dataviz skill's mark specs. */
17
- const BAR_CORNER_RADIUS_PIXELS = 4;
18
- /** A 2px surface gap between neighbouring fills (dataviz skill). */
19
- const FILL_GAP_PIXELS = 2;
20
- /** An x-axis title sits this far below the axis, clear of its one row of labels. */
21
- const X_AXIS_NAME_GAP_PIXELS = 28;
22
- /** …plus this much clear space. */
23
- const Y_AXIS_NAME_CLEARANCE_PIXELS = 18;
24
- const PANEL_TITLE_FONT_PIXELS = 13;
25
- /** How far above its panel a panel title sits, in pixels. */
26
- const PANEL_TITLE_OFFSET_PIXELS = 20;
27
- /** How far right of its panel a colour scale sits, in pixels. */
28
- const COLOUR_SCALE_OFFSET_PIXELS = 50;
29
- const COLOUR_SCALE_HEIGHT_PIXELS = 90;
30
- /** The legend sits below the figure title when there is one. */
31
- const LEGEND_BELOW_TITLE_PIXELS = 28;
32
- /**
33
- * A histogram's bars sit at their bin centres on a value axis, where ECharts
34
- * makes the band as wide as the smallest gap between bar positions: one bin.
35
- * No gap inside the band or between colour groups, so the groups tile each
36
- * bin edge to edge, and a bin's bars cover exactly its range at any zoom.
37
- */
38
- const HISTOGRAM_BAR_GAP = "0%";
39
- /**
40
- * A single bin has no gap to measure, so its edges stand in as empty positions
41
- * half a bin from its centre: the band is then half a bin, and a gap of minus
42
- * one band widens the bars back to the whole bin. ECharts measures the gap over
43
- * every bar series on the axis, so the edges sit in a companion series that
44
- * the tooltip and axis pointer skip, stacked with the bin so it adds no column.
45
- */
46
- const SINGLE_BIN_BAND_GAP = "-100%";
47
- /** Histogram points are [centre, height, start, end]: x reads all three, so a bin stays while any of it is in a zoom window. */
48
- const HISTOGRAM_X_DIMENSIONS = [0, 2, 3];
49
- const HISTOGRAM_HEIGHT_DIMENSION = 1;
50
- /** Keeps any point with one of its x dimensions in the window; for one x dimension it is ECharts' default "filter". */
51
- const ZOOM_FILTER_MODE = "weakFilter";
52
- /** Scatter and bar points are [x, y, colourValue]: the colour value is at index 2. */
53
- const COLOUR_VALUE_DIMENSION = 2;
54
-
55
- /** Heatmap cells are [x, y, colourValue, value]: the real value, for the tooltip, is at index 3. */
56
- const HEATMAP_REAL_VALUE_DIMENSION = 3;
57
-
58
- /** Density points are [longitude, latitude, weight]: the weight is at index 2. */
59
- const DENSITY_WEIGHT_DIMENSION = 2;
60
-
61
- /** Where there is no weight, the heat fades to nothing rather than tinting the whole map. */
62
- const DENSITY_EMPTY_COLOUR = "rgba(0, 0, 0, 0)";
63
-
64
- const ECHARTS_SYMBOLS: Record<MarkerShape, string> = {
65
- circle: "circle",
66
- square: "rect",
67
- triangle: "triangle",
68
- diamond: "diamond",
69
- cross: "path://M4,0h2v4h4v2h-4v4h-2v-4h-4v-2h4z",
70
- star: "path://M5,0l1.2,3.6h3.8l-3.1,2.3l1.2,3.7l-3.1-2.3l-3.1,2.3l1.2-3.7l-3.1-2.3h3.8z",
71
- };
72
-
73
- function convertDash(dash: LineDash): string | number[] {
74
- return dash === "dash_dot" ? DASH_DOT_PATTERN : dash;
75
- }
76
-
77
- function percent(fraction: number): string {
78
- return `${(fraction * PERCENT).toFixed(2)}%`;
79
- }
80
-
81
- function formatBinEdge(value: number): string {
82
- return Number.isInteger(value) ? String(value) : value.toPrecision(3);
83
- }
84
-
85
- function buildAxis(axis: AxisModel, options: { theme: PlotTheme; gridIndex: number; direction: "x" | "y" }): Record<string, unknown> {
86
- const ink = PLOT_THEMES[options.theme];
87
- const type = axis.kind === "value" && axis.scale === "log" ? "log" : axis.kind;
88
- return {
89
- gridIndex: options.gridIndex,
90
- type,
91
- name: axis.label,
92
- nameLocation: "middle",
93
- nameGap: options.direction === "x"
94
- ? X_AXIS_NAME_GAP_PIXELS
95
- : axis.longestLabelCharacters * AXIS_LABEL_CHARACTER_PIXELS + Y_AXIS_NAME_CLEARANCE_PIXELS,
96
- nameTextStyle: { color: ink.textSecondary },
97
- // PLAIN_NUMBERS_LABEL_KEY: the page swaps in a plain formatter (2005, not 2,005);
98
- // ECharts applies its thousands separator even to string templates.
99
- axisLabel: { color: ink.textSecondary, ...(axis.isYearLike ? { [PLAIN_NUMBERS_LABEL_KEY]: true } : {}) },
100
- axisLine: { lineStyle: { color: ink.gridLine } },
101
- splitLine: { lineStyle: { color: ink.gridLine } },
102
- ...(type === "category" ? { data: axis.categories } : {}),
103
- // "scale" lets the axis leave out zero; bars and densities must keep it.
104
- ...(type === "value" ? { scale: !axis.includesZero } : {}),
105
- };
106
- }
107
-
108
- function buildSeries(series: SeriesModel, options: { theme: PlotTheme; index: number; panelIndex: number }): Record<string, unknown>[] {
109
- const ink = PLOT_THEMES[options.theme];
110
- const axes = { xAxisIndex: options.index, yAxisIndex: options.index };
111
- switch (series.mark) {
112
- case "line":
113
- // With no colour, the panel's colour scale shades the line by each point's value.
114
- return [{
115
- type: "line", ...axes, name: series.name, data: series.points.map((point) => [point.x, point.y, point.colourValue]),
116
- showSymbol: series.showMarkers, symbolSize: MARKER_SIZE,
117
- ...(series.colour === null ? {} : { itemStyle: { color: series.colour } }),
118
- lineStyle: { width: LINE_WIDTH, type: convertDash(series.dash), ...(series.colour === null ? {} : { color: series.colour }) },
119
- ...(series.isFilled ? { areaStyle: { opacity: FILLED_AREA_OPACITY } } : {}),
120
- }];
121
- case "scatter": {
122
- return [{
123
- type: "scatter", ...axes, name: series.name, symbol: ECHARTS_SYMBOLS[series.shape],
124
- data: series.points.map((point) => ({
125
- value: [point.x, point.y, point.colourValue],
126
- symbolSize: point.sizePixels,
127
- })),
128
- itemStyle: { borderColor: ink.surface, borderWidth: FILL_GAP_PIXELS / 2, ...(series.colour === null ? {} : { color: series.colour }) },
129
- }];
130
- }
131
- case "bar":
132
- return [{
133
- type: "bar", ...axes, name: series.name,
134
- ...(series.isStacked ? { stack: `panel-${options.panelIndex}` } : {}),
135
- data: series.points.map((point) => ({ value: series.isHorizontal ? [point.y, point.x, point.colourValue] : [point.x, point.y, point.colourValue] })),
136
- itemStyle: { borderRadius: BAR_CORNER_RADIUS_PIXELS, borderColor: ink.surface, borderWidth: FILL_GAP_PIXELS / 2, ...(series.colour === null ? {} : { color: series.colour }) },
137
- }];
138
- case "box":
139
- return [
140
- {
141
- type: "boxplot", ...axes, name: series.name, itemStyle: { color: "transparent", borderColor: series.colour, borderWidth: LINE_WIDTH },
142
- data: series.boxes.map((box) => ({
143
- name: box.category,
144
- value: [box.summary.lowerWhisker, box.summary.firstQuartile, box.summary.median, box.summary.thirdQuartile, box.summary.upperWhisker],
145
- })),
146
- },
147
- {
148
- type: "scatter", ...axes, name: series.name, symbolSize: MARKER_SIZE, itemStyle: { color: series.colour },
149
- data: series.boxes.flatMap((box) => (series.showMarkers ? box.values : box.summary.outliers).map((value) => [box.category, value])),
150
- },
151
- ];
152
- case "histogram": {
153
- const isSingleBin = series.bins.length === 1;
154
- const gaps = { barGap: HISTOGRAM_BAR_GAP, barCategoryGap: isSingleBin ? SINGLE_BIN_BAND_GAP : HISTOGRAM_BAR_GAP };
155
- const stack = isSingleBin ? { stack: `panel-${options.panelIndex}-histogram-${series.name}` } : {};
156
- const bins = {
157
- type: "bar", ...axes, name: series.name, ...gaps, ...stack,
158
- // Named by its range, so the tooltip reads "3–12" rather than the bin's centre.
159
- data: series.bins.map((bin) => ({ name: `${formatBinEdge(bin.start)}–${formatBinEdge(bin.end)}`, value: [(bin.start + bin.end) / 2, bin.height, bin.start, bin.end] })),
160
- encode: { x: HISTOGRAM_X_DIMENSIONS, y: HISTOGRAM_HEIGHT_DIMENSION, tooltip: HISTOGRAM_HEIGHT_DIMENSION },
161
- itemStyle: { color: series.colour, borderColor: ink.surface, borderWidth: FILL_GAP_PIXELS / 2, borderRadius: [BAR_CORNER_RADIUS_PIXELS, BAR_CORNER_RADIUS_PIXELS, 0, 0] },
162
- };
163
- if (!isSingleBin) return [bins];
164
- const edges = {
165
- type: "bar", ...axes, name: series.name, ...gaps, ...stack, silent: true, tooltip: { show: false },
166
- data: series.bins.flatMap((bin) => [[bin.start, null], [bin.end, null]]),
167
- };
168
- return [bins, edges];
169
- }
170
- case "heatmap":
171
- // Colour follows the colour value; the tooltip shows the real one.
172
- return [{
173
- type: "heatmap", ...axes, name: series.name, encode: { x: 0, y: 1, tooltip: HEATMAP_REAL_VALUE_DIMENSION },
174
- data: series.cells.map((cell) => [cell.x, cell.y, cell.colourValue, cell.value]),
175
- }];
176
- case "pie":
177
- return [];
178
- }
179
- }
180
-
181
- /**
182
- * Keys the ECharts option carries for the page that draws it, beyond ECharts'
183
- * own: the maps to register before drawing (name → GeoJSON, or "world" for
184
- * the world outline the page loads), a notice for the person, and on an axis
185
- * label, that its numbers are years to print without separators. The page
186
- * acts on each and removes it before handing the option to ECharts.
187
- */
188
- export const MAPS_OPTION_KEY = "plotillaMaps";
189
- /** The option key holding a notice the page shows the person, then removes. */
190
- export const NOTICE_OPTION_KEY = "plotillaNotice";
191
- /** The axis-label key telling the page to show plain numbers (2005, not 2,005), then removed. */
192
- export const PLAIN_NUMBERS_LABEL_KEY = "plotillaPlainNumbers";
193
-
194
- /**
195
- * Build the ECharts option for a figure.
196
- *
197
- * @param model - The chart model.
198
- * @param options - The size the host draws the figure at, in pixels; build again when it changes.
199
- * @returns The option object.
200
- */
201
- export function buildEChartsOption(model: FigureModel, options: { size: FigureSize }): Record<string, unknown> {
202
- const ink = PLOT_THEMES[model.theme];
203
- const { size } = options;
204
- const rectangles = computePanelRectangles(model, { size });
205
- const grids: Record<string, unknown>[] = [];
206
- const xAxes: Record<string, unknown>[] = [];
207
- const yAxes: Record<string, unknown>[] = [];
208
- const allSeries: Record<string, unknown>[] = [];
209
- const titles: Record<string, unknown>[] = model.title === null ? [] : [{ text: model.title, left: "center", top: 0, textStyle: { color: ink.textPrimary } }];
210
- const visualMaps: Record<string, unknown>[] = [];
211
- const geos: Record<string, unknown>[] = [];
212
- let maps: EChartsMapParts["maps"] = {};
213
- const notices: string[] = [];
214
- let axisIndex = 0;
215
-
216
- model.panels.forEach((panel: PanelModel, panelIndex) => {
217
- const rectangle = rectangles[panelIndex];
218
- if (rectangle === undefined) throw new Error(`Expected a rectangle for panel ${panelIndex}; got none.`);
219
- if (panel.title !== null) {
220
- titles.push({ text: panel.title, left: percent(rectangle.left), top: percent(rectangle.top - PANEL_TITLE_OFFSET_PIXELS / size.height), textStyle: { color: ink.textPrimary, fontSize: PANEL_TITLE_FONT_PIXELS } });
221
- }
222
-
223
- if (panel.map !== undefined) {
224
- const parts = buildEChartsMap({ ...panel, map: panel.map }, { panelIndex, geoIndex: geos.length, rectangle, theme: model.theme });
225
- const offset = allSeries.length;
226
- geos.push(parts.geo);
227
- allSeries.push(...parts.series);
228
- maps = { ...maps, ...parts.maps };
229
- if (parts.notice !== null) notices.push(parts.notice);
230
- // Heat runs from nothing to the heaviest place, apart from any colour scale the panel shows.
231
- for (const density of parts.densitySeries) {
232
- visualMaps.push({
233
- type: "continuous", show: false, min: 0, max: density.maximumWeight, dimension: DENSITY_WEIGHT_DIMENSION,
234
- seriesIndex: [density.index + offset], inRange: { color: [DENSITY_EMPTY_COLOUR, ...SEQUENTIAL_COLOURS] },
235
- });
236
- }
237
- if (panel.colourScale !== null && parts.scaledSeries.length > 0) {
238
- visualMaps.push({
239
- type: "continuous", min: panel.colourScale.minimum, max: panel.colourScale.maximum,
240
- seriesIndex: parts.scaledSeries.map((index) => index + offset),
241
- // Real values at the ends, even when colour follows a log or rank.
242
- inRange: { color: [...panel.colourScale.colours] },
243
- text: buildColourLegendText(panel.colourScale),
244
- textStyle: { color: ink.textSecondary }, calculable: false,
245
- orient: "vertical", left: percent(rectangle.left), bottom: percent(1 - rectangle.top - rectangle.height), itemHeight: COLOUR_SCALE_HEIGHT_PIXELS,
246
- });
247
- }
248
- return;
249
- }
250
-
251
- const pie = panel.series.find((series) => series.mark === "pie");
252
- if (pie !== undefined && pie.mark === "pie") {
253
- const radius = Math.min(rectangle.width, rectangle.height) / 2;
254
- allSeries.push({
255
- type: "pie", name: pie.name,
256
- center: [percent(rectangle.left + rectangle.width / 2), percent(rectangle.top + rectangle.height / 2)],
257
- radius: [percent(radius * pie.hole), percent(radius)],
258
- itemStyle: { borderColor: ink.surface, borderWidth: FILL_GAP_PIXELS },
259
- label: { color: ink.textSecondary },
260
- data: pie.slices.map((slice) => ({ name: slice.label, value: slice.value, itemStyle: { color: slice.colour } })),
261
- });
262
- return;
263
- }
264
-
265
- grids.push({ left: percent(rectangle.left), top: percent(rectangle.top), width: percent(rectangle.width), height: percent(rectangle.height) });
266
- if (panel.xAxis !== null) xAxes.push(buildAxis(panel.xAxis, { theme: model.theme, gridIndex: axisIndex, direction: "x" }));
267
- if (panel.yAxis !== null) yAxes.push(buildAxis(panel.yAxis, { theme: model.theme, gridIndex: axisIndex, direction: "y" }));
268
- const coloured: number[] = [];
269
- for (const series of panel.series) {
270
- const built = buildSeries(series, { theme: model.theme, index: axisIndex, panelIndex });
271
- // The colour scale drives only series coloured by a number (and heatmaps), never a trend line beside them.
272
- const isScaled = series.mark === "heatmap" || ("colour" in series && series.colour === null);
273
- if (isScaled) coloured.push(...built.map((_, offset) => allSeries.length + offset));
274
- allSeries.push(...built);
275
- }
276
- if (panel.colourScale !== null) {
277
- visualMaps.push({
278
- type: "continuous", min: panel.colourScale.minimum, max: panel.colourScale.maximum, dimension: COLOUR_VALUE_DIMENSION,
279
- // Handles would show transformed numbers on a log or rank scale, so only a linear scale gets them.
280
- seriesIndex: coloured, calculable: panel.colourScale.ticks === undefined,
281
- inRange: { color: [...panel.colourScale.colours] }, text: buildColourLegendText(panel.colourScale), textStyle: { color: ink.textSecondary },
282
- orient: "vertical", right: percent(1 - rectangle.left - rectangle.width - COLOUR_SCALE_OFFSET_PIXELS / size.width), top: percent(rectangle.top), itemHeight: COLOUR_SCALE_HEIGHT_PIXELS,
283
- });
284
- }
285
- axisIndex += 1;
286
- });
287
-
288
- const hasLines = model.panels.some((panel) => panel.series.some((series) => series.mark === "line"));
289
- const hasItemOnly = model.panels.some((panel) => panel.series.some((series) => series.mark === "pie" || series.mark === "heatmap" || series.mark === "box"));
290
- return {
291
- backgroundColor: ink.surface,
292
- textStyle: { color: ink.textPrimary },
293
- title: titles,
294
- legend: model.legendNames.length >= MINIMUM_SERIES_FOR_LEGEND
295
- ? { data: model.legendNames, top: model.title === null ? 0 : LEGEND_BELOW_TITLE_PIXELS, textStyle: { color: ink.textSecondary } }
296
- : { show: false },
297
- tooltip: hasLines && !hasItemOnly ? { trigger: "axis", axisPointer: { type: "cross" } } : { trigger: "item" },
298
- ...(model.isXAxisShared ? { axisPointer: { link: [{ xAxisIndex: "all" }] } } : {}),
299
- // Shared axes zoom together: one inside zoom drives every x axis, or every y axis.
300
- ...(model.isXAxisShared || model.isYAxisShared ? {
301
- dataZoom: [
302
- ...(model.isXAxisShared ? [{ type: "inside", xAxisIndex: xAxes.map((_, index) => index), filterMode: ZOOM_FILTER_MODE }] : []),
303
- ...(model.isYAxisShared ? [{ type: "inside", yAxisIndex: yAxes.map((_, index) => index) }] : []),
304
- ],
305
- } : {}),
306
- grid: grids,
307
- xAxis: xAxes,
308
- yAxis: yAxes,
309
- visualMap: visualMaps,
310
- ...(geos.length === 0 ? {} : { geo: geos }),
311
- series: allSeries,
312
- // For the page, which cannot receive functions or register maps through JSON:
313
- // outlines to register before drawing, and anything to tell the person.
314
- ...(Object.keys(maps).length === 0 ? {} : { [MAPS_OPTION_KEY]: maps }),
315
- ...(notices.length === 0 ? {} : { [NOTICE_OPTION_KEY]: notices.join(" ") }),
316
- };
317
- }
@@ -1,170 +0,0 @@
1
- /**
2
- * A map panel → Plotly traces and the layout entry for its subplot.
3
- *
4
- * Flat maps use Plotly's tile maps (scattermap, choroplethmap, densitymap)
5
- * over an OpenFreeMap street map; the globe uses Plotly's geo subplot with an
6
- * orthographic projection (country outlines, no street tiles).
7
- */
8
-
9
- import type { MapModel } from "../model/panel_model";
10
- import { pickNoDataColour } from "../model/map_model";
11
- import { MAP_INKS, MAP_LABEL_FONT, MAP_STYLE_URLS, MARKER_SIZE, PLOT_THEMES, pickSequentialColour, type PlotTheme } from "../colour/palette";
12
- import type { PanelModel } from "../model/panel_model";
13
-
14
- /** How far each point spreads on a density map, in pixels. */
15
- const DENSITY_RADIUS_PIXELS = 18;
16
- const REGION_OPACITY = 0.78;
17
-
18
- /** Space between a panel and its colour bar, as a fraction of the figure's width. */
19
- const COLOUR_BAR_GAP = 0.005;
20
- /** How thick a colour bar is. */
21
- const COLOUR_BAR_THICKNESS_PIXELS = 14;
22
-
23
- /**
24
- * A panel's Plotly colour bar: beside the panel and as tall as it, so panels
25
- * in a grid never stack their bars (panel_layout leaves room for it), with
26
- * ticks in real values when the scale transforms them (log, quantile).
27
- *
28
- * @param scale - The panel's colour scale, if any.
29
- * @param options - The panel's domain.
30
- * @returns The colorbar to give the panel's coloured traces.
31
- */
32
- export function buildColourBar(
33
- scale: PanelModel["colourScale"] | undefined,
34
- options: { domain: { x: [number, number]; y: [number, number] } },
35
- ): Record<string, unknown> {
36
- const ticks = scale === null || scale === undefined || scale.ticks === undefined
37
- ? {}
38
- : { tickvals: scale.ticks.map((tick) => tick.value), ticktext: scale.ticks.map((tick) => tick.text) };
39
- return {
40
- title: { text: scale?.label ?? "" },
41
- x: options.domain.x[1] + COLOUR_BAR_GAP, xanchor: "left",
42
- y: (options.domain.y[0] + options.domain.y[1]) / 2, yanchor: "middle",
43
- len: options.domain.y[1] - options.domain.y[0], lenmode: "fraction", thickness: COLOUR_BAR_THICKNESS_PIXELS,
44
- ...ticks,
45
- };
46
- }
47
-
48
- /**
49
- * Build a map panel's traces and subplot layout for Plotly.
50
- *
51
- * @param panel - A panel with a map.
52
- * @param options - The subplot suffix ("" or "2", …), its domain, the theme,
53
- * and the colour scale as Plotly wants it.
54
- * @returns The traces, and the layout key and value for the subplot.
55
- */
56
- export function buildPlotlyMap(
57
- panel: PanelModel & { map: MapModel },
58
- options: { suffix: string; domain: { x: [number, number]; y: [number, number] }; theme: PlotTheme; colourScale: [number, string][] | null },
59
- ): { traces: Record<string, unknown>[]; layoutKey: string; layoutValue: Record<string, unknown> } {
60
- const map = panel.map;
61
- const ink = PLOT_THEMES[options.theme];
62
- const isGlobe = map.projection === "globe";
63
- const subplot = isGlobe ? { geo: `geo${options.suffix}` } : { subplot: `map${options.suffix}` };
64
- const scale = panel.colourScale;
65
- const traces: Record<string, unknown>[] = [];
66
- const colourBar = buildColourBar(scale, { domain: options.domain });
67
- let hasScaleShown = false;
68
- const showScaleOnce = (): boolean => {
69
- const show = !hasScaleShown;
70
- hasScaleShown = true;
71
- return show;
72
- };
73
-
74
- for (const layer of map.layers) {
75
- if (layer.kind === "points") {
76
- const hasLabels = layer.points.some((point) => point.label !== null);
77
- const sizes = layer.points.map((point) => point.sizePixels);
78
- traces.push({
79
- type: isGlobe ? "scattergeo" : "scattermap", ...subplot, name: layer.name,
80
- lon: layer.points.map((point) => point.longitude), lat: layer.points.map((point) => point.latitude),
81
- mode: hasLabels ? "markers+text" : "markers", text: layer.points.map((point) => point.label ?? ""),
82
- // Street maps draw labels with the tile server's own fonts.
83
- textposition: "top right", textfont: { color: ink.textPrimary, ...(isGlobe ? {} : { family: MAP_LABEL_FONT }) },
84
- marker: layer.colour === null
85
- ? { size: sizes, color: layer.points.map((point) => point.colourValue), colorscale: options.colourScale, showscale: showScaleOnce(), cmin: scale?.minimum, cmax: scale?.maximum, colorbar: colourBar }
86
- : { size: sizes, color: layer.colour },
87
- });
88
- } else if (layer.kind === "density") {
89
- traces.push({
90
- type: "densitymap", ...subplot, name: layer.name, showlegend: false,
91
- lon: layer.points.map((point) => point.longitude), lat: layer.points.map((point) => point.latitude),
92
- z: layer.points.map((point) => point.weight), radius: DENSITY_RADIUS_PIXELS,
93
- colorscale: options.colourScale ?? [[0, "rgba(0,0,0,0)"], [0.2, pickSequentialColour(0.3)], [1, pickSequentialColour(1)]],
94
- showscale: false,
95
- });
96
- } else if (layer.kind === "regions") {
97
- const common = { ...subplot, geojson: layer.geojson, featureidkey: "properties.plotilla_id", hoverinfo: "text", showlegend: false };
98
- const regionType = isGlobe ? "choropleth" : "choroplethmap";
99
- const line = { color: ink.surface, width: 1 };
100
- const valued = layer.regions.filter((region) => region.value !== null);
101
- if (valued.length > 0) {
102
- traces.push({
103
- type: regionType, ...common, name: layer.name, locations: valued.map((region) => region.id), z: valued.map((region) => region.value),
104
- text: valued.map((region) => region.label), colorscale: options.colourScale, showscale: showScaleOnce(),
105
- zmin: scale?.minimum, zmax: scale?.maximum, colorbar: colourBar, marker: { opacity: REGION_OPACITY, line },
106
- });
107
- }
108
- // Regions coloured by category, and those with no data, each drawn in their fixed colour.
109
- const byColour = new Map<string, typeof layer.regions>();
110
- for (const region of layer.regions) {
111
- if (region.value !== null) continue;
112
- const colour = region.colour ?? pickNoDataColour(options.theme);
113
- byColour.set(colour, [...(byColour.get(colour) ?? []), region]);
114
- }
115
- for (const [colour, regions] of byColour) {
116
- traces.push({
117
- type: regionType, ...common, name: layer.name, locations: regions.map((region) => region.id), z: regions.map(() => 0),
118
- text: regions.map((region) => region.label), colorscale: [[0, colour], [1, colour]], showscale: false,
119
- marker: { opacity: REGION_OPACITY, line },
120
- });
121
- }
122
- } else {
123
- layer.lines.forEach((line) => {
124
- const colour = layer.colour ?? (scale === null || line.colourValue === null
125
- ? ink.textSecondary
126
- : pickSequentialColour((line.colourValue - scale.minimum) / (scale.maximum - scale.minimum || 1)));
127
- traces.push({
128
- type: isGlobe ? "scattergeo" : "scattermap", ...subplot, name: layer.name, mode: "lines",
129
- lon: line.path.map(([longitude]) => longitude), lat: line.path.map(([, latitude]) => latitude),
130
- line: { color: colour, width: line.widthPixels },
131
- hoverinfo: "text", text: line.label ?? layer.name,
132
- });
133
- });
134
- // A line trace has one colour and no colour bar, so lines coloured by a number get one
135
- // invisible marker per line, at its start, that carries the panel's colour bar.
136
- if (layer.colour === null && scale !== null) {
137
- traces.push({
138
- type: isGlobe ? "scattergeo" : "scattermap", ...subplot, name: layer.name, mode: "markers",
139
- lon: layer.lines.map((line) => line.path[0]?.[0] ?? null), lat: layer.lines.map((line) => line.path[0]?.[1] ?? null),
140
- marker: {
141
- size: MARKER_SIZE, opacity: 0, color: layer.lines.map((line) => line.colourValue),
142
- colorscale: options.colourScale, showscale: showScaleOnce(), cmin: scale.minimum, cmax: scale.maximum, colorbar: colourBar,
143
- },
144
- hoverinfo: "skip", showlegend: false,
145
- });
146
- }
147
- }
148
- }
149
-
150
- if (isGlobe) {
151
- const land = MAP_INKS[options.theme];
152
- return {
153
- traces,
154
- layoutKey: `geo${options.suffix}`,
155
- layoutValue: {
156
- domain: options.domain,
157
- // The globe starts whole, turned to face the data; closer only if the agent asked.
158
- projection: { type: "orthographic", rotation: { lon: map.centre[0], lat: map.centre[1] }, scale: map.isZoomGiven ? Math.max(1, 2 ** (map.zoom - 1)) : 1 },
159
- showland: true, landcolor: land.land, showocean: true, oceancolor: land.water,
160
- showcountries: true, countrycolor: land.border, coastlinecolor: land.border,
161
- showlakes: false, showframe: false, bgcolor: ink.surface,
162
- },
163
- };
164
- }
165
- return {
166
- traces,
167
- layoutKey: `map${options.suffix}`,
168
- layoutValue: { domain: options.domain, style: MAP_STYLE_URLS[options.theme], center: { lon: map.centre[0], lat: map.centre[1] }, zoom: map.zoom },
169
- };
170
- }