plotilla 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/data/boundaries/canada_provinces.geojson +1 -0
- package/data/boundaries/eu_countries.geojson +1 -0
- package/data/boundaries/us_states.geojson +1 -0
- package/data/boundaries/world_countries.geojson +1 -0
- package/package.json +62 -4
- package/src/colour/colour_scale.ts +80 -0
- package/src/colour/palette.ts +220 -0
- package/src/examples/example_figures.ts +320 -0
- package/src/fields/axis_fields.ts +32 -0
- package/src/fields/colour_fields.ts +40 -0
- package/src/fields/column_fields.ts +64 -0
- package/src/fields/common_fields.ts +13 -0
- package/src/fields/decide_plot_axes.ts +77 -0
- package/src/fields/marker_fields.ts +16 -0
- package/src/figure/plot_figure.ts +67 -0
- package/src/figure/resolve_plot_figure.ts +47 -0
- package/src/figure/validate_plot_figure.ts +412 -0
- package/src/map/boundary_sets.ts +116 -0
- package/src/map/check_map_layers.ts +32 -0
- package/src/map/fetch_region_outlines.ts +48 -0
- package/src/map/geojson.ts +174 -0
- package/src/map/map_layers.ts +108 -0
- package/src/model/check_axis_shows_years.ts +58 -0
- package/src/model/map_model.ts +238 -0
- package/src/model/panel_layout.ts +171 -0
- package/src/model/panel_model.ts +85 -0
- package/src/model/plot_model.ts +347 -0
- package/src/model/statistics.ts +134 -0
- package/src/plots/bar_plot.ts +36 -0
- package/src/plots/box_plot.ts +26 -0
- package/src/plots/density_plot.ts +29 -0
- package/src/plots/heatmap_plot.ts +24 -0
- package/src/plots/histogram_plot.ts +29 -0
- package/src/plots/line_plot.ts +29 -0
- package/src/plots/map_plot.ts +46 -0
- package/src/plots/pie_plot.ts +23 -0
- package/src/plots/scatter_plot.ts +32 -0
- package/src/renderers/echarts_map.ts +194 -0
- package/src/renderers/echarts_options.ts +317 -0
- package/src/renderers/plotly_map.ts +170 -0
- package/src/renderers/plotly_options.ts +318 -0
- package/src/table/check_column.ts +34 -0
- package/src/table/check_values_have_spread.ts +47 -0
- package/src/table/compute_quantile.ts +23 -0
- package/src/table/data_table.ts +83 -0
- package/src/table/density_bandwidth.ts +94 -0
- package/src/table/find_line_fit.ts +44 -0
- package/src/table/get_number_range.ts +21 -0
- package/src/table/group_rows.ts +71 -0
- package/src/table/list_categories.ts +17 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The statistics plots need, computed here so both renderers draw
|
|
3
|
+
* identical numbers: box-plot summaries, histogram bins, and kernel density.
|
|
4
|
+
*
|
|
5
|
+
* Density is computed here rather than by a renderer: Plotly has trouble
|
|
6
|
+
* with several densities in one plot and ECharts has none
|
|
7
|
+
* (scribble.tube's .documents/concepts/plot_spec.md).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { computeQuantile } from "../table/compute_quantile";
|
|
11
|
+
import { computeDensityNormaliser } from "../table/density_bandwidth";
|
|
12
|
+
import { checkValuesHaveSpread, computeStandardDeviation } from "../table/check_values_have_spread";
|
|
13
|
+
import { findLineFit, type FitPoint, type LineFit } from "../table/find_line_fit";
|
|
14
|
+
|
|
15
|
+
/** Tukey's whisker reach, in interquartile ranges. */
|
|
16
|
+
export const WHISKER_IQR_MULTIPLE = 1.5;
|
|
17
|
+
|
|
18
|
+
/** Points at which a density curve is evaluated. */
|
|
19
|
+
export const DENSITY_POINTS = 200;
|
|
20
|
+
|
|
21
|
+
/** A box plot's five numbers and its outliers. */
|
|
22
|
+
export type BoxSummary = {
|
|
23
|
+
lowerWhisker: number;
|
|
24
|
+
firstQuartile: number;
|
|
25
|
+
median: number;
|
|
26
|
+
thirdQuartile: number;
|
|
27
|
+
upperWhisker: number;
|
|
28
|
+
outliers: number[];
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** One histogram bar: [start, end) and its height. */
|
|
32
|
+
export type HistogramBin = { start: number; end: number; height: number };
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Summarise values for a box plot (Tukey: whiskers reach the furthest value
|
|
36
|
+
* within 1.5 IQR of the box; beyond that are outliers).
|
|
37
|
+
*
|
|
38
|
+
* @param values - The values; at least one.
|
|
39
|
+
* @returns The summary.
|
|
40
|
+
*/
|
|
41
|
+
export function summariseBox(values: number[]): BoxSummary {
|
|
42
|
+
const sorted = [...values].sort((first, second) => first - second);
|
|
43
|
+
const firstQuartile = computeQuantile(sorted, { quantile: 0.25 });
|
|
44
|
+
const median = computeQuantile(sorted, { quantile: 0.5 });
|
|
45
|
+
const thirdQuartile = computeQuantile(sorted, { quantile: 0.75 });
|
|
46
|
+
const reach = WHISKER_IQR_MULTIPLE * (thirdQuartile - firstQuartile);
|
|
47
|
+
const inside = sorted.filter((value) => value >= firstQuartile - reach && value <= thirdQuartile + reach);
|
|
48
|
+
return {
|
|
49
|
+
lowerWhisker: inside[0] as number,
|
|
50
|
+
firstQuartile,
|
|
51
|
+
median,
|
|
52
|
+
thirdQuartile,
|
|
53
|
+
upperWhisker: inside[inside.length - 1] as number,
|
|
54
|
+
outliers: sorted.filter((value) => value < firstQuartile - reach || value > thirdQuartile + reach),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Choose a bin count by Sturges' rule, ceil(log2 n) + 1.
|
|
60
|
+
*
|
|
61
|
+
* @param count - How many values.
|
|
62
|
+
* @returns The number of bins.
|
|
63
|
+
*/
|
|
64
|
+
export function chooseBinCount(count: number): number {
|
|
65
|
+
return count <= 1 ? 1 : Math.ceil(Math.log2(count)) + 1;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Bin values for a histogram.
|
|
70
|
+
*
|
|
71
|
+
* @param values - The values; at least one.
|
|
72
|
+
* @param options - The bin count, the shared range (so several groups line
|
|
73
|
+
* up), and whether heights are densities (area 1) rather than counts.
|
|
74
|
+
* @returns The bins, in order.
|
|
75
|
+
*/
|
|
76
|
+
export function binValues(
|
|
77
|
+
values: number[],
|
|
78
|
+
options: { binCount: number; minimum: number; maximum: number; isNormalised: boolean },
|
|
79
|
+
): HistogramBin[] {
|
|
80
|
+
const width = options.maximum > options.minimum ? (options.maximum - options.minimum) / options.binCount : 1;
|
|
81
|
+
const counts = new Array<number>(options.binCount).fill(0);
|
|
82
|
+
for (const value of values) {
|
|
83
|
+
// The top edge belongs to the last bin.
|
|
84
|
+
const index = Math.min(Math.floor((value - options.minimum) / width), options.binCount - 1);
|
|
85
|
+
counts[index] = (counts[index] as number) + 1;
|
|
86
|
+
}
|
|
87
|
+
return counts.map((count, index) => ({
|
|
88
|
+
start: options.minimum + index * width,
|
|
89
|
+
end: options.minimum + (index + 1) * width,
|
|
90
|
+
height: options.isNormalised ? count / (values.length * width) : count,
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Estimate a density curve with a Gaussian kernel.
|
|
96
|
+
*
|
|
97
|
+
* @param values - The values; at least two.
|
|
98
|
+
* @param options - The bandwidth, and the x range to evaluate over (shared
|
|
99
|
+
* across groups so their curves line up).
|
|
100
|
+
* @returns Points along the curve, in x order.
|
|
101
|
+
*/
|
|
102
|
+
export function estimateDensity(
|
|
103
|
+
values: number[],
|
|
104
|
+
options: { bandwidth: number; minimum: number; maximum: number; pointCount?: number },
|
|
105
|
+
): { x: number; y: number }[] {
|
|
106
|
+
const pointCount = options.pointCount ?? DENSITY_POINTS;
|
|
107
|
+
const normaliser = computeDensityNormaliser({ count: values.length, bandwidth: options.bandwidth });
|
|
108
|
+
const step = (options.maximum - options.minimum) / (pointCount - 1);
|
|
109
|
+
const points: { x: number; y: number }[] = [];
|
|
110
|
+
for (let index = 0; index < pointCount; index += 1) {
|
|
111
|
+
const x = options.minimum + index * step;
|
|
112
|
+
let sum = 0;
|
|
113
|
+
for (const value of values) {
|
|
114
|
+
const distance = (x - value) / options.bandwidth;
|
|
115
|
+
sum += Math.exp(-0.5 * distance * distance);
|
|
116
|
+
}
|
|
117
|
+
points.push({ x, y: sum * normaliser });
|
|
118
|
+
}
|
|
119
|
+
return points;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Fit a least-squares line, for a series validation has already judged
|
|
124
|
+
* fittable by the same rule; failing here means validation missed a case.
|
|
125
|
+
*
|
|
126
|
+
* @param points - Points whose fit is finite (see findLineFit).
|
|
127
|
+
* @returns The slope, intercept and the line's ends.
|
|
128
|
+
* @throws Error when the points have no finite fit.
|
|
129
|
+
*/
|
|
130
|
+
export function fitLine(points: readonly FitPoint[]): LineFit {
|
|
131
|
+
const fit = findLineFit(points);
|
|
132
|
+
if (fit === null) throw new Error("A trend line needs x values that vary measurably, with a finite fit; validation should have refused this series.");
|
|
133
|
+
return fit;
|
|
134
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The bar plot: a bar per category, grouped or stacked by colour. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS, COLOUR_SCALE_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { X_FIELD, Y_FIELD } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
|
|
9
|
+
/** How bars of different colours share a category. */
|
|
10
|
+
export const BAR_MODES = ["grouped", "stacked"] as const;
|
|
11
|
+
/** The mode bars get when the agent names none. */
|
|
12
|
+
export const DEFAULT_BAR_MODE: (typeof BAR_MODES)[number] = "grouped";
|
|
13
|
+
/** Whether bars stand up or lie down. */
|
|
14
|
+
export const BAR_ORIENTATIONS = ["vertical", "horizontal"] as const;
|
|
15
|
+
/** The orientation bars get when the agent names none. */
|
|
16
|
+
export const DEFAULT_BAR_ORIENTATION: (typeof BAR_ORIENTATIONS)[number] = "vertical";
|
|
17
|
+
|
|
18
|
+
/** A bar plot as an agent sends it. */
|
|
19
|
+
export const BAR_PLOT_SCHEMA = z.strictObject({
|
|
20
|
+
type: z.literal("bar"),
|
|
21
|
+
...COMMON_FIELDS,
|
|
22
|
+
...AXIS_LABEL_FIELDS,
|
|
23
|
+
...Y_SCALE_FIELDS,
|
|
24
|
+
...COLOUR_FIELDS,
|
|
25
|
+
...COLOUR_SCALE_FIELDS,
|
|
26
|
+
x: X_FIELD,
|
|
27
|
+
y: Y_FIELD,
|
|
28
|
+
mode: z.enum(BAR_MODES).default(DEFAULT_BAR_MODE).describe("How bars of different colours share a category: side by side, or one on another."),
|
|
29
|
+
orientation: z.enum(BAR_ORIENTATIONS).default(DEFAULT_BAR_ORIENTATION).describe("Whether bars stand up or lie along the x axis."),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
/** A bar plot, through the schema. */
|
|
33
|
+
export type BarPlot = z.infer<typeof BAR_PLOT_SCHEMA>;
|
|
34
|
+
|
|
35
|
+
/** The column fields that must hold numbers. */
|
|
36
|
+
export const BAR_NUMERIC_COLUMNS: readonly (keyof BarPlot)[] = ["y"];
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** The box plot: a box summarising y: quartiles, whiskers at 1.5 interquartile ranges, outliers. One box per x category. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { X_FIELD, Y_FIELD } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
import { MARKER_FIELDS } from "../fields/marker_fields";
|
|
9
|
+
|
|
10
|
+
/** A box plot as an agent sends it. */
|
|
11
|
+
export const BOX_PLOT_SCHEMA = z.strictObject({
|
|
12
|
+
type: z.literal("box"),
|
|
13
|
+
...COMMON_FIELDS,
|
|
14
|
+
...AXIS_LABEL_FIELDS,
|
|
15
|
+
...Y_SCALE_FIELDS,
|
|
16
|
+
...COLOUR_FIELDS,
|
|
17
|
+
...MARKER_FIELDS,
|
|
18
|
+
y: Y_FIELD,
|
|
19
|
+
x: X_FIELD.optional(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
/** A box plot, through the schema. */
|
|
23
|
+
export type BoxPlot = z.infer<typeof BOX_PLOT_SCHEMA>;
|
|
24
|
+
|
|
25
|
+
/** The column fields that must hold numbers. */
|
|
26
|
+
export const BOX_NUMERIC_COLUMNS: readonly (keyof BoxPlot)[] = ["y"];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** The density plot: a smooth curve of how x is spread (kernel density), one per colour category. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, X_SCALE_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { X_FIELD } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
|
|
9
|
+
/** Whether a density curve is filled when the agent does not say: no. */
|
|
10
|
+
export const DEFAULT_SHOW_AREA = false;
|
|
11
|
+
|
|
12
|
+
/** A density plot as an agent sends it. */
|
|
13
|
+
export const DENSITY_PLOT_SCHEMA = z.strictObject({
|
|
14
|
+
type: z.literal("density"),
|
|
15
|
+
...COMMON_FIELDS,
|
|
16
|
+
...AXIS_LABEL_FIELDS,
|
|
17
|
+
...X_SCALE_FIELDS,
|
|
18
|
+
...Y_SCALE_FIELDS,
|
|
19
|
+
...COLOUR_FIELDS,
|
|
20
|
+
x: X_FIELD,
|
|
21
|
+
bandwidth: z.number().positive().optional().describe("How smooth the curve is, in x's units. Default: Silverman's rule, from the data."),
|
|
22
|
+
show_area: z.boolean().default(DEFAULT_SHOW_AREA).describe("Fill the area under each curve."),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** A density plot, through the schema. */
|
|
26
|
+
export type DensityPlot = z.infer<typeof DENSITY_PLOT_SCHEMA>;
|
|
27
|
+
|
|
28
|
+
/** The column fields that must hold numbers. */
|
|
29
|
+
export const DENSITY_NUMERIC_COLUMNS: readonly (keyof DensityPlot)[] = ["x"];
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The heatmap plot: a grid of cells, one row of the table per cell, coloured by value. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_SCALE_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { VALUE_FIELD, X_FIELD, Y_FIELD } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
|
|
9
|
+
/** A heatmap as an agent sends it. */
|
|
10
|
+
export const HEATMAP_PLOT_SCHEMA = z.strictObject({
|
|
11
|
+
type: z.literal("heatmap"),
|
|
12
|
+
...COMMON_FIELDS,
|
|
13
|
+
...AXIS_LABEL_FIELDS,
|
|
14
|
+
...COLOUR_SCALE_FIELDS,
|
|
15
|
+
x: X_FIELD,
|
|
16
|
+
y: Y_FIELD,
|
|
17
|
+
value: VALUE_FIELD,
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
/** A heatmap, through the schema. */
|
|
21
|
+
export type HeatmapPlot = z.infer<typeof HEATMAP_PLOT_SCHEMA>;
|
|
22
|
+
|
|
23
|
+
/** The column fields that must hold numbers. */
|
|
24
|
+
export const HEATMAP_NUMERIC_COLUMNS: readonly (keyof HeatmapPlot)[] = ["value"];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** The histogram plot: counts of x in equal-width bins, one set of bars per colour category on one shared range. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { X_FIELD } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
|
|
9
|
+
/** Whether a histogram is scaled to area 1 when the agent does not say: no. */
|
|
10
|
+
export const DEFAULT_IS_NORMALISED = false;
|
|
11
|
+
|
|
12
|
+
/** A histogram as an agent sends it. */
|
|
13
|
+
export const HISTOGRAM_PLOT_SCHEMA = z.strictObject({
|
|
14
|
+
type: z.literal("histogram"),
|
|
15
|
+
...COMMON_FIELDS,
|
|
16
|
+
...AXIS_LABEL_FIELDS,
|
|
17
|
+
// No x_scale: bins are equal widths on a linear axis, the same in both renderers.
|
|
18
|
+
...Y_SCALE_FIELDS,
|
|
19
|
+
...COLOUR_FIELDS,
|
|
20
|
+
x: X_FIELD,
|
|
21
|
+
bins: z.number().int().min(1).optional().describe("How many bins. Default: Sturges' rule, from the row count."),
|
|
22
|
+
is_normalised: z.boolean().default(DEFAULT_IS_NORMALISED).describe("Scale heights so the bars' area is 1, to compare groups of different sizes."),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** A histogram, through the schema. */
|
|
26
|
+
export type HistogramPlot = z.infer<typeof HISTOGRAM_PLOT_SCHEMA>;
|
|
27
|
+
|
|
28
|
+
/** The column fields that must hold numbers. */
|
|
29
|
+
export const HISTOGRAM_NUMERIC_COLUMNS: readonly (keyof HistogramPlot)[] = ["x"];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** The line plot: a line through the points in x order, one line per colour category. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, X_SCALE_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS, COLOUR_SCALE_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { X_FIELD, Y_FIELD, defineColumnField } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
import { MARKER_FIELDS } from "../fields/marker_fields";
|
|
9
|
+
|
|
10
|
+
/** A line plot as an agent sends it. */
|
|
11
|
+
export const LINE_PLOT_SCHEMA = z.strictObject({
|
|
12
|
+
type: z.literal("line"),
|
|
13
|
+
...COMMON_FIELDS,
|
|
14
|
+
...AXIS_LABEL_FIELDS,
|
|
15
|
+
...X_SCALE_FIELDS,
|
|
16
|
+
...Y_SCALE_FIELDS,
|
|
17
|
+
...COLOUR_FIELDS,
|
|
18
|
+
...COLOUR_SCALE_FIELDS,
|
|
19
|
+
...MARKER_FIELDS,
|
|
20
|
+
x: X_FIELD,
|
|
21
|
+
y: Y_FIELD,
|
|
22
|
+
line_type: defineColumnField("A column whose categories each get their own dash.").optional(),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** A line plot, through the schema. */
|
|
26
|
+
export type LinePlot = z.infer<typeof LINE_PLOT_SCHEMA>;
|
|
27
|
+
|
|
28
|
+
/** The column fields that must hold numbers. */
|
|
29
|
+
export const LINE_NUMERIC_COLUMNS: readonly (keyof LinePlot)[] = ["y"];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The map plot: layers of points, density, regions and lines. Without a centre and zoom, it fits everything shown. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
5
|
+
import { MAP_LAYER_SCHEMA } from "../map/map_layers";
|
|
6
|
+
|
|
7
|
+
/** How a map is drawn: flat, or as a globe. */
|
|
8
|
+
export const MAP_PROJECTIONS = ["flat", "globe"] as const;
|
|
9
|
+
/** One of MAP_PROJECTIONS. */
|
|
10
|
+
export type MapProjection = (typeof MAP_PROJECTIONS)[number];
|
|
11
|
+
/** The projection a map gets when the agent names none. */
|
|
12
|
+
export const DEFAULT_MAP_PROJECTION: MapProjection = "flat";
|
|
13
|
+
|
|
14
|
+
/** The most zoomed-in a map may start: street level. */
|
|
15
|
+
export const MAXIMUM_MAP_ZOOM = 20;
|
|
16
|
+
|
|
17
|
+
/** The widest a longitude and a latitude can be, in degrees. */
|
|
18
|
+
const MAXIMUM_LONGITUDE = 180;
|
|
19
|
+
const MAXIMUM_LATITUDE = 90;
|
|
20
|
+
|
|
21
|
+
/** A map plot as an agent sends it. */
|
|
22
|
+
export const MAP_PLOT_SCHEMA = z.strictObject({
|
|
23
|
+
type: z.literal("map"),
|
|
24
|
+
...COMMON_FIELDS,
|
|
25
|
+
projection: z
|
|
26
|
+
.enum(MAP_PROJECTIONS)
|
|
27
|
+
.default(DEFAULT_MAP_PROJECTION)
|
|
28
|
+
.describe("A flat, zoomable street map, or a globe you can spin."),
|
|
29
|
+
centre: z
|
|
30
|
+
.tuple([z.number().min(-MAXIMUM_LONGITUDE).max(MAXIMUM_LONGITUDE), z.number().min(-MAXIMUM_LATITUDE).max(MAXIMUM_LATITUDE)])
|
|
31
|
+
.optional()
|
|
32
|
+
.describe("Where the view starts, [longitude, latitude] in degrees. Default: fitted to everything shown."),
|
|
33
|
+
zoom: z
|
|
34
|
+
.number()
|
|
35
|
+
.min(0)
|
|
36
|
+
.max(MAXIMUM_MAP_ZOOM)
|
|
37
|
+
.optional()
|
|
38
|
+
.describe(`How close the view starts: 0 is the whole world, ${MAXIMUM_MAP_ZOOM} street level. Default: fitted to everything shown.`),
|
|
39
|
+
layers: z.array(MAP_LAYER_SCHEMA).min(1, "a map needs at least one layer.").describe("The layers, drawn regions first, then density, lines and points."),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** A map plot, through the schema. */
|
|
43
|
+
export type MapPlot = z.infer<typeof MAP_PLOT_SCHEMA>;
|
|
44
|
+
|
|
45
|
+
/** The column fields that must hold numbers: a map's columns are on its layers. */
|
|
46
|
+
export const MAP_NUMERIC_COLUMNS: readonly (keyof MapPlot)[] = [];
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The pie plot: slices of a whole, one per row; a donut when it has a hole. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { LABEL_FIELD, VALUE_FIELD } from "../fields/column_fields";
|
|
5
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
6
|
+
|
|
7
|
+
/** A pie's hole when the agent names none: none, a full pie. */
|
|
8
|
+
export const DEFAULT_HOLE = 0;
|
|
9
|
+
|
|
10
|
+
/** A pie plot as an agent sends it. */
|
|
11
|
+
export const PIE_PLOT_SCHEMA = z.strictObject({
|
|
12
|
+
type: z.literal("pie"),
|
|
13
|
+
...COMMON_FIELDS,
|
|
14
|
+
label: LABEL_FIELD,
|
|
15
|
+
value: VALUE_FIELD,
|
|
16
|
+
hole: z.number().min(0).lt(1).default(DEFAULT_HOLE).describe("The hole's share of the radius: 0 for a pie, up to 1 for a donut."),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
/** A pie plot, through the schema. */
|
|
20
|
+
export type PiePlot = z.infer<typeof PIE_PLOT_SCHEMA>;
|
|
21
|
+
|
|
22
|
+
/** The column fields that must hold numbers. */
|
|
23
|
+
export const PIE_NUMERIC_COLUMNS: readonly (keyof PiePlot)[] = ["value"];
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** The scatter plot: a point per row. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AXIS_LABEL_FIELDS, X_SCALE_FIELDS, Y_SCALE_FIELDS } from "../fields/axis_fields";
|
|
5
|
+
import { COLOUR_FIELDS, COLOUR_SCALE_FIELDS } from "../fields/colour_fields";
|
|
6
|
+
import { SIZE_FIELD, X_FIELD, Y_FIELD, defineColumnField } from "../fields/column_fields";
|
|
7
|
+
import { COMMON_FIELDS } from "../fields/common_fields";
|
|
8
|
+
|
|
9
|
+
/** Whether a scatter gets a trend line when the agent does not say: no. */
|
|
10
|
+
export const DEFAULT_SHOW_TREND_LINE = false;
|
|
11
|
+
|
|
12
|
+
/** A scatter plot as an agent sends it. */
|
|
13
|
+
export const SCATTER_PLOT_SCHEMA = z.strictObject({
|
|
14
|
+
type: z.literal("scatter"),
|
|
15
|
+
...COMMON_FIELDS,
|
|
16
|
+
...AXIS_LABEL_FIELDS,
|
|
17
|
+
...X_SCALE_FIELDS,
|
|
18
|
+
...Y_SCALE_FIELDS,
|
|
19
|
+
...COLOUR_FIELDS,
|
|
20
|
+
...COLOUR_SCALE_FIELDS,
|
|
21
|
+
x: X_FIELD,
|
|
22
|
+
y: Y_FIELD,
|
|
23
|
+
marker_shape: defineColumnField("A column whose categories each get their own marker shape.").optional(),
|
|
24
|
+
size: SIZE_FIELD.optional(),
|
|
25
|
+
show_trend_line: z.boolean().default(DEFAULT_SHOW_TREND_LINE).describe("Draw a least-squares line per combination of colour category and marker_shape category (one line when neither splits the points)."),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/** A scatter plot, through the schema. */
|
|
29
|
+
export type ScatterPlot = z.infer<typeof SCATTER_PLOT_SCHEMA>;
|
|
30
|
+
|
|
31
|
+
/** The column fields that must hold numbers. */
|
|
32
|
+
export const SCATTER_NUMERIC_COLUMNS: readonly (keyof ScatterPlot)[] = ["y", "size"];
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A map panel → an ECharts geo component and its series.
|
|
3
|
+
*
|
|
4
|
+
* ECharts draws maps over GeoJSON outlines, not street tiles: every regions
|
|
5
|
+
* layer's outlines, merged into one registered map under the panel's geo, or
|
|
6
|
+
* a world map (registered by the page) under points and lines. Drag and
|
|
7
|
+
* scroll to pan and zoom. ECharts has no globe; a globe map is drawn flat
|
|
8
|
+
* here, and the page says so (Plotly draws the globe).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { FeatureCollection } from "../map/geojson";
|
|
12
|
+
import { getNumberRange } from "../table/get_number_range";
|
|
13
|
+
import type { MapLayerModel, MapModel } from "../model/panel_model";
|
|
14
|
+
import { HEXADECIMAL, interpolateRampColour, MAP_INKS, PLOT_THEMES, pickSequentialColour, type PlotTheme } from "../colour/palette";
|
|
15
|
+
import type { PanelModel } from "../model/panel_model";
|
|
16
|
+
import { pickNoDataColour } from "../model/map_model";
|
|
17
|
+
import type { PanelRectangle } from "../model/panel_layout";
|
|
18
|
+
|
|
19
|
+
/** The name the page registers the world outline under (see viewer_items.js). */
|
|
20
|
+
export const WORLD_MAP_NAME = "plotilla-world";
|
|
21
|
+
|
|
22
|
+
/** How much wider than the data the starting view is, as a fraction of its span. */
|
|
23
|
+
const BOUNDS_PADDING_FRACTION = 0.08;
|
|
24
|
+
const PERCENT = 100;
|
|
25
|
+
|
|
26
|
+
function percent(fraction: number): string {
|
|
27
|
+
return `${(fraction * PERCENT).toFixed(2)}%`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Registered regions maps are named this, then a hash of their outlines. */
|
|
31
|
+
const REGIONS_MAP_NAME_PREFIX = "plotilla-regions-";
|
|
32
|
+
|
|
33
|
+
/** 32-bit FNV-1a: small, fast, and spreads near-identical outlines apart. */
|
|
34
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
35
|
+
const FNV_PRIME = 0x01000193;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Hash text to a short stable name part.
|
|
39
|
+
*
|
|
40
|
+
* @param text - The text, here a GeoJSON's JSON.
|
|
41
|
+
* @returns The 32-bit FNV-1a hash, in hexadecimal.
|
|
42
|
+
*/
|
|
43
|
+
function hashText(text: string): string {
|
|
44
|
+
let hash = FNV_OFFSET_BASIS;
|
|
45
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
46
|
+
hash ^= text.charCodeAt(index);
|
|
47
|
+
hash = Math.imul(hash, FNV_PRIME);
|
|
48
|
+
}
|
|
49
|
+
return (hash >>> 0).toString(HEXADECIMAL);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A map layer of regions, whose outlines ECharts must register. */
|
|
53
|
+
type RegionsLayerModel = Extract<MapLayerModel, { kind: "regions" }>;
|
|
54
|
+
|
|
55
|
+
/** What an ECharts map panel adds to the option. */
|
|
56
|
+
export type EChartsMapParts = {
|
|
57
|
+
geo: Record<string, unknown>;
|
|
58
|
+
series: Record<string, unknown>[];
|
|
59
|
+
/** Indices (within `series`) the panel's colour scale drives. */
|
|
60
|
+
scaledSeries: number[];
|
|
61
|
+
/** Density series (indices within `series`), each needing its own visual map: ECharts draws no heatmap without one. */
|
|
62
|
+
densitySeries: { index: number; maximumWeight: number }[];
|
|
63
|
+
/** Outlines the page must register before drawing: a GeoJSON, or "world". */
|
|
64
|
+
maps: Record<string, FeatureCollection | "world">;
|
|
65
|
+
notice: string | null;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Build a map panel's geo component and series for ECharts.
|
|
70
|
+
*
|
|
71
|
+
* @param panel - A panel with a map.
|
|
72
|
+
* @param options - Its index (for geo and series references), its rectangle, and the theme.
|
|
73
|
+
* @returns The parts to merge into the option.
|
|
74
|
+
*/
|
|
75
|
+
export function buildEChartsMap(
|
|
76
|
+
panel: PanelModel & { map: MapModel },
|
|
77
|
+
options: { panelIndex: number; geoIndex: number; rectangle: PanelRectangle; theme: PlotTheme },
|
|
78
|
+
): EChartsMapParts {
|
|
79
|
+
const map = panel.map;
|
|
80
|
+
const ink = PLOT_THEMES[options.theme];
|
|
81
|
+
const land = MAP_INKS[options.theme];
|
|
82
|
+
const scale = panel.colourScale;
|
|
83
|
+
// Every regions layer's outlines go in one registered map under one geo, so all layers share one view
|
|
84
|
+
// (ECharts keeps no two geos' pan and zoom together). Feature ids are unique across layers
|
|
85
|
+
// ("<layer>:<feature>"), so each layer's series names only its own regions.
|
|
86
|
+
const regionsLayers = map.layers.flatMap((layer) => (layer.kind === "regions" ? [layer] : []));
|
|
87
|
+
const outlines: FeatureCollection | null = regionsLayers.length === 0 ? null
|
|
88
|
+
: regionsLayers.length === 1 ? (regionsLayers[0] as RegionsLayerModel).geojson
|
|
89
|
+
: { type: "FeatureCollection", features: regionsLayers.flatMap((layer) => layer.geojson.features) };
|
|
90
|
+
// Named by content: a page registers maps globally, so two figures' outlines must never share a name.
|
|
91
|
+
const mapName = outlines === null ? WORLD_MAP_NAME : `${REGIONS_MAP_NAME_PREFIX}${hashText(JSON.stringify(outlines))}`;
|
|
92
|
+
const maps: EChartsMapParts["maps"] = outlines === null ? { [WORLD_MAP_NAME]: "world" } : { [mapName]: outlines };
|
|
93
|
+
|
|
94
|
+
// A layer's region with no data takes the no-data colour, as in Plotly; outlines in no layer keep the land colour.
|
|
95
|
+
const paintedRegions = regionsLayers.flatMap((layer) => layer.regions.map((region) => ({
|
|
96
|
+
name: region.id,
|
|
97
|
+
itemStyle: {
|
|
98
|
+
areaColor: region.colour ?? (region.value === null || scale === null ? pickNoDataColour(options.theme)
|
|
99
|
+
: interpolateRampColour(region.value, { minimum: scale.minimum, maximum: scale.maximum, colours: scale.colours })),
|
|
100
|
+
},
|
|
101
|
+
})));
|
|
102
|
+
|
|
103
|
+
const bounds = map.bounds;
|
|
104
|
+
const pad = bounds === null ? 0 : Math.max(bounds[2] - bounds[0], bounds[3] - bounds[1]) * BOUNDS_PADDING_FRACTION;
|
|
105
|
+
const geo: Record<string, unknown> = {
|
|
106
|
+
map: mapName,
|
|
107
|
+
roam: true,
|
|
108
|
+
nameProperty: "plotilla_id",
|
|
109
|
+
left: percent(options.rectangle.left), top: percent(options.rectangle.top),
|
|
110
|
+
width: percent(options.rectangle.width), height: percent(options.rectangle.height),
|
|
111
|
+
...(bounds === null ? {} : { boundingCoords: [[bounds[0] - pad, bounds[3] + pad], [bounds[2] + pad, bounds[1] - pad]] }),
|
|
112
|
+
itemStyle: { areaColor: land.land, borderColor: land.border, borderWidth: 0.6 },
|
|
113
|
+
emphasis: { label: { show: false }, itemStyle: { areaColor: land.land, borderColor: ink.textSecondary } },
|
|
114
|
+
select: { disabled: true },
|
|
115
|
+
label: { show: false },
|
|
116
|
+
// The geo paints every region, not the map series on it: it reads each region's style from here,
|
|
117
|
+
// and a series' data item colours are never read (ECharts' MapDraw). So every region's colour,
|
|
118
|
+
// by category, along the panel's scale, or for no data, is given here; the visualMap only draws the colour bar.
|
|
119
|
+
...(paintedRegions.length === 0 ? {} : { regions: paintedRegions }),
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const series: Record<string, unknown>[] = [];
|
|
123
|
+
const scaledSeries: number[] = [];
|
|
124
|
+
const densitySeries: EChartsMapParts["densitySeries"] = [];
|
|
125
|
+
const geoTarget = { geoIndex: options.geoIndex };
|
|
126
|
+
// A geo lets a visualMap repaint its regions only through the first map series on it, and then
|
|
127
|
+
// repaints every region, giving one missing from that series the series' default colour. So a
|
|
128
|
+
// regions layer coloured by category, when there is one, comes first: no visualMap reaches the
|
|
129
|
+
// geo, and every region keeps the colour set above. Alone, the scaled layer is first and its
|
|
130
|
+
// visualMap repaints each region in the same colour. Outlines draw in the registered map's order,
|
|
131
|
+
// so this reorders no shapes.
|
|
132
|
+
const isScaledRegions = (layer: MapLayerModel): boolean => layer.kind === "regions" && layer.regions.some((region) => region.value !== null);
|
|
133
|
+
const layers = [
|
|
134
|
+
...map.layers.filter((layer) => layer.kind === "regions" && !isScaledRegions(layer)),
|
|
135
|
+
...map.layers.filter(isScaledRegions),
|
|
136
|
+
...map.layers.filter((layer) => layer.kind !== "regions"),
|
|
137
|
+
];
|
|
138
|
+
for (const layer of layers) {
|
|
139
|
+
if (layer.kind === "regions") {
|
|
140
|
+
if (isScaledRegions(layer)) scaledSeries.push(series.length);
|
|
141
|
+
series.push({
|
|
142
|
+
type: "map", ...geoTarget, name: layer.name,
|
|
143
|
+
data: layer.regions.map((region) => ({
|
|
144
|
+
name: region.id, value: region.value ?? undefined, label: region.label,
|
|
145
|
+
...(region.colour === null ? {} : { itemStyle: { areaColor: region.colour } }),
|
|
146
|
+
})),
|
|
147
|
+
});
|
|
148
|
+
} else if (layer.kind === "points") {
|
|
149
|
+
const hasLabels = layer.points.some((point) => point.label !== null);
|
|
150
|
+
if (layer.colour === null) scaledSeries.push(series.length);
|
|
151
|
+
series.push({
|
|
152
|
+
type: "scatter", coordinateSystem: "geo", ...geoTarget, name: layer.name,
|
|
153
|
+
data: layer.points.map((point) => ({
|
|
154
|
+
name: point.label ?? "", value: [point.longitude, point.latitude, point.colourValue],
|
|
155
|
+
symbolSize: point.sizePixels,
|
|
156
|
+
})),
|
|
157
|
+
itemStyle: { borderColor: ink.surface, borderWidth: 1, ...(layer.colour === null ? {} : { color: layer.colour }) },
|
|
158
|
+
label: { show: hasLabels, formatter: "{b}", position: "right", color: ink.textPrimary },
|
|
159
|
+
});
|
|
160
|
+
} else if (layer.kind === "density") {
|
|
161
|
+
// Nothing to draw, and ECharts cannot range a heat scale with no positive weight; the model tells the agent.
|
|
162
|
+
const maximumWeight = Math.max(0, getNumberRange(layer.points.map((point) => point.weight)).maximum);
|
|
163
|
+
if (maximumWeight <= 0) continue;
|
|
164
|
+
densitySeries.push({ index: series.length, maximumWeight });
|
|
165
|
+
series.push({
|
|
166
|
+
type: "heatmap", coordinateSystem: "geo", ...geoTarget, name: layer.name,
|
|
167
|
+
data: layer.points.map((point) => [point.longitude, point.latitude, point.weight]),
|
|
168
|
+
pointSize: 10, blurSize: 18,
|
|
169
|
+
});
|
|
170
|
+
} else {
|
|
171
|
+
// Lines coloured by a number join the panel's colour legend; each keeps its own colour, from its value.
|
|
172
|
+
const isScaledLines = layer.colour === null && scale !== null;
|
|
173
|
+
if (isScaledLines) scaledSeries.push(series.length);
|
|
174
|
+
series.push({
|
|
175
|
+
type: "lines", coordinateSystem: "geo", ...geoTarget, name: layer.name, polyline: true,
|
|
176
|
+
data: layer.lines.map((line) => ({
|
|
177
|
+
name: line.label ?? layer.name, coords: line.path, ...(isScaledLines && line.colourValue !== null ? { value: line.colourValue } : {}),
|
|
178
|
+
// ECharts draws lines at half opacity by default, which would not match the legend's colours.
|
|
179
|
+
lineStyle: {
|
|
180
|
+
opacity: 1,
|
|
181
|
+
width: line.widthPixels,
|
|
182
|
+
color: layer.colour ?? (scale === null || line.colourValue === null
|
|
183
|
+
? ink.textSecondary
|
|
184
|
+
: pickSequentialColour((line.colourValue - scale.minimum) / (scale.maximum - scale.minimum || 1))),
|
|
185
|
+
},
|
|
186
|
+
})),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
geo, series, scaledSeries, densitySeries, maps,
|
|
192
|
+
notice: map.projection === "globe" ? "ECharts has no globe, so this map is flat. Switch to Plotly for the globe." : null,
|
|
193
|
+
};
|
|
194
|
+
}
|