@tetrascience-npm/ts-lib-viz 0.0.0-stage → 0.1.4

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 (278) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2171 -2
  3. package/dist/src/builder/PlotPanel.d.ts +42 -0
  4. package/dist/src/builder/PlotPanel.js +433 -0
  5. package/dist/src/builder/Popover.d.ts +37 -0
  6. package/dist/src/builder/Popover.js +32 -0
  7. package/dist/src/builder/Stepper.d.ts +21 -0
  8. package/dist/src/builder/Stepper.js +41 -0
  9. package/dist/src/builder/index.d.ts +10 -0
  10. package/dist/src/builder/index.js +10 -0
  11. package/dist/src/core/adapters.d.ts +86 -0
  12. package/dist/src/core/adapters.js +219 -0
  13. package/dist/src/core/aggregate.d.ts +74 -0
  14. package/dist/src/core/aggregate.js +102 -0
  15. package/dist/src/core/annotations.d.ts +34 -0
  16. package/dist/src/core/annotations.js +71 -0
  17. package/dist/src/core/band-order.d.ts +86 -0
  18. package/dist/src/core/band-order.js +132 -0
  19. package/dist/src/core/binning.d.ts +123 -0
  20. package/dist/src/core/binning.js +193 -0
  21. package/dist/src/core/bounds.d.ts +40 -0
  22. package/dist/src/core/bounds.js +107 -0
  23. package/dist/src/core/brush.d.ts +73 -0
  24. package/dist/src/core/brush.js +102 -0
  25. package/dist/src/core/build.d.ts +322 -0
  26. package/dist/src/core/build.js +496 -0
  27. package/dist/src/core/camera.d.ts +152 -0
  28. package/dist/src/core/camera.js +303 -0
  29. package/dist/src/core/capabilities.d.ts +24 -0
  30. package/dist/src/core/capabilities.js +307 -0
  31. package/dist/src/core/chord.d.ts +49 -0
  32. package/dist/src/core/chord.js +57 -0
  33. package/dist/src/core/circular.d.ts +83 -0
  34. package/dist/src/core/circular.js +63 -0
  35. package/dist/src/core/cluster.d.ts +136 -0
  36. package/dist/src/core/cluster.js +607 -0
  37. package/dist/src/core/critique.d.ts +92 -0
  38. package/dist/src/core/critique.js +905 -0
  39. package/dist/src/core/density.d.ts +38 -0
  40. package/dist/src/core/density.js +82 -0
  41. package/dist/src/core/figure-set.d.ts +34 -0
  42. package/dist/src/core/figure-set.js +55 -0
  43. package/dist/src/core/finding-codes.d.ts +10 -0
  44. package/dist/src/core/finding-codes.js +1 -0
  45. package/dist/src/core/fit-types.d.ts +46 -0
  46. package/dist/src/core/fit-types.js +7 -0
  47. package/dist/src/core/fitter.d.ts +62 -0
  48. package/dist/src/core/fitter.js +102 -0
  49. package/dist/src/core/frame-geometry.d.ts +407 -0
  50. package/dist/src/core/frame-geometry.js +612 -0
  51. package/dist/src/core/frame.d.ts +329 -0
  52. package/dist/src/core/frame.js +1432 -0
  53. package/dist/src/core/geom-table.d.ts +503 -0
  54. package/dist/src/core/geom-table.js +484 -0
  55. package/dist/src/core/geom-types.d.ts +182 -0
  56. package/dist/src/core/geom-types.js +17 -0
  57. package/dist/src/core/grammar.d.ts +359 -0
  58. package/dist/src/core/grammar.js +397 -0
  59. package/dist/src/core/heat-reductions.d.ts +36 -0
  60. package/dist/src/core/heat-reductions.js +133 -0
  61. package/dist/src/core/hexbin.d.ts +84 -0
  62. package/dist/src/core/hexbin.js +168 -0
  63. package/dist/src/core/hierarchy.d.ts +59 -0
  64. package/dist/src/core/hierarchy.js +248 -0
  65. package/dist/src/core/hit.d.ts +75 -0
  66. package/dist/src/core/hit.js +37 -0
  67. package/dist/src/core/index.d.ts +33 -0
  68. package/dist/src/core/index.js +18 -0
  69. package/dist/src/core/internal.d.ts +58 -0
  70. package/dist/src/core/internal.js +58 -0
  71. package/dist/src/core/labels.d.ts +37 -0
  72. package/dist/src/core/labels.js +54 -0
  73. package/dist/src/core/layers.d.ts +594 -0
  74. package/dist/src/core/layers.js +2892 -0
  75. package/dist/src/core/load.d.ts +17 -0
  76. package/dist/src/core/load.js +356 -0
  77. package/dist/src/core/marginal.d.ts +65 -0
  78. package/dist/src/core/marginal.js +116 -0
  79. package/dist/src/core/mesh.d.ts +69 -0
  80. package/dist/src/core/mesh.js +237 -0
  81. package/dist/src/core/omission.d.ts +41 -0
  82. package/dist/src/core/omission.js +62 -0
  83. package/dist/src/core/palette-sets.d.ts +623 -0
  84. package/dist/src/core/palette-sets.js +1058 -0
  85. package/dist/src/core/palette.d.ts +871 -0
  86. package/dist/src/core/palette.js +511 -0
  87. package/dist/src/core/plot-data.d.ts +71 -0
  88. package/dist/src/core/plot-data.js +82 -0
  89. package/dist/src/core/predicate.d.ts +50 -0
  90. package/dist/src/core/predicate.js +20 -0
  91. package/dist/src/core/profile.d.ts +111 -0
  92. package/dist/src/core/profile.js +221 -0
  93. package/dist/src/core/readout.d.ts +108 -0
  94. package/dist/src/core/readout.js +215 -0
  95. package/dist/src/core/region.d.ts +56 -0
  96. package/dist/src/core/region.js +101 -0
  97. package/dist/src/core/rings.d.ts +96 -0
  98. package/dist/src/core/rings.js +171 -0
  99. package/dist/src/core/rules.d.ts +45 -0
  100. package/dist/src/core/rules.js +69 -0
  101. package/dist/src/core/sankey.d.ts +49 -0
  102. package/dist/src/core/sankey.js +96 -0
  103. package/dist/src/core/select.d.ts +52 -0
  104. package/dist/src/core/select.js +216 -0
  105. package/dist/src/core/side-track.d.ts +98 -0
  106. package/dist/src/core/side-track.js +197 -0
  107. package/dist/src/core/sizing.d.ts +54 -0
  108. package/dist/src/core/sizing.js +37 -0
  109. package/dist/src/core/spec-edit.d.ts +68 -0
  110. package/dist/src/core/spec-edit.js +105 -0
  111. package/dist/src/core/spec.d.ts +1111 -0
  112. package/dist/src/core/spec.js +39 -0
  113. package/dist/src/core/stats.d.ts +161 -0
  114. package/dist/src/core/stats.js +318 -0
  115. package/dist/src/core/tick-format.d.ts +21 -0
  116. package/dist/src/core/tick-format.js +87 -0
  117. package/dist/src/core/tokens.d.ts +47 -0
  118. package/dist/src/core/tokens.js +138 -0
  119. package/dist/src/core/transform.d.ts +21 -0
  120. package/dist/src/core/transform.js +19 -0
  121. package/dist/src/core/voxels.d.ts +53 -0
  122. package/dist/src/core/voxels.js +129 -0
  123. package/dist/src/core/zoom.d.ts +76 -0
  124. package/dist/src/core/zoom.js +103 -0
  125. package/dist/src/graph/GraphSurface.d.ts +127 -0
  126. package/dist/src/graph/GraphSurface.js +423 -0
  127. package/dist/src/graph/data.d.ts +103 -0
  128. package/dist/src/graph/data.js +140 -0
  129. package/dist/src/graph/index.d.ts +7 -0
  130. package/dist/src/graph/index.js +7 -0
  131. package/dist/src/mcp/data.d.ts +28 -0
  132. package/dist/src/mcp/data.js +131 -0
  133. package/dist/src/mcp/index.d.ts +7 -0
  134. package/dist/src/mcp/index.js +7 -0
  135. package/dist/src/mcp/paths.d.ts +12 -0
  136. package/dist/src/mcp/paths.js +30 -0
  137. package/dist/src/mcp/render.d.ts +67 -0
  138. package/dist/src/mcp/render.js +189 -0
  139. package/dist/src/mcp/server.d.ts +7 -0
  140. package/dist/src/mcp/server.js +25 -0
  141. package/dist/src/mcp/tools.d.ts +82 -0
  142. package/dist/src/mcp/tools.js +412 -0
  143. package/dist/src/react/BrushLayer.d.ts +20 -0
  144. package/dist/src/react/BrushLayer.js +98 -0
  145. package/dist/src/react/ColorLegend.d.ts +45 -0
  146. package/dist/src/react/ColorLegend.js +64 -0
  147. package/dist/src/react/Figure.d.ts +19 -0
  148. package/dist/src/react/Figure.js +6 -0
  149. package/dist/src/react/Frame.d.ts +87 -0
  150. package/dist/src/react/Frame.js +192 -0
  151. package/dist/src/react/MarkLegend.d.ts +32 -0
  152. package/dist/src/react/MarkLegend.js +24 -0
  153. package/dist/src/react/SeriesLegend.d.ts +38 -0
  154. package/dist/src/react/SeriesLegend.js +27 -0
  155. package/dist/src/react/SizeLegend.d.ts +24 -0
  156. package/dist/src/react/SizeLegend.js +25 -0
  157. package/dist/src/react/Toolbar.d.ts +109 -0
  158. package/dist/src/react/Toolbar.js +483 -0
  159. package/dist/src/react/Tooltip.d.ts +37 -0
  160. package/dist/src/react/Tooltip.js +59 -0
  161. package/dist/src/react/Viz.d.ts +112 -0
  162. package/dist/src/react/Viz.js +1311 -0
  163. package/dist/src/react/export.d.ts +32 -0
  164. package/dist/src/react/export.js +181 -0
  165. package/dist/src/react/geoms/Area.d.ts +38 -0
  166. package/dist/src/react/geoms/Area.js +48 -0
  167. package/dist/src/react/geoms/Bars.d.ts +130 -0
  168. package/dist/src/react/geoms/Bars.js +164 -0
  169. package/dist/src/react/geoms/Box.d.ts +50 -0
  170. package/dist/src/react/geoms/Box.js +32 -0
  171. package/dist/src/react/geoms/Chord.d.ts +60 -0
  172. package/dist/src/react/geoms/Chord.js +78 -0
  173. package/dist/src/react/geoms/Contour.d.ts +44 -0
  174. package/dist/src/react/geoms/Contour.js +78 -0
  175. package/dist/src/react/geoms/DensityCurve.d.ts +30 -0
  176. package/dist/src/react/geoms/DensityCurve.js +38 -0
  177. package/dist/src/react/geoms/FitCurve.d.ts +26 -0
  178. package/dist/src/react/geoms/FitCurve.js +52 -0
  179. package/dist/src/react/geoms/Freqpoly.d.ts +30 -0
  180. package/dist/src/react/geoms/Freqpoly.js +45 -0
  181. package/dist/src/react/geoms/Gauge.d.ts +42 -0
  182. package/dist/src/react/geoms/Gauge.js +90 -0
  183. package/dist/src/react/geoms/Heatmap.d.ts +79 -0
  184. package/dist/src/react/geoms/Heatmap.js +51 -0
  185. package/dist/src/react/geoms/Hexbin.d.ts +74 -0
  186. package/dist/src/react/geoms/Hexbin.js +89 -0
  187. package/dist/src/react/geoms/Icicle.d.ts +38 -0
  188. package/dist/src/react/geoms/Icicle.js +9 -0
  189. package/dist/src/react/geoms/Ideogram.d.ts +58 -0
  190. package/dist/src/react/geoms/Ideogram.js +77 -0
  191. package/dist/src/react/geoms/Interval.d.ts +28 -0
  192. package/dist/src/react/geoms/Interval.js +39 -0
  193. package/dist/src/react/geoms/Line.d.ts +39 -0
  194. package/dist/src/react/geoms/Line.js +52 -0
  195. package/dist/src/react/geoms/Parallel.d.ts +38 -0
  196. package/dist/src/react/geoms/Parallel.js +131 -0
  197. package/dist/src/react/geoms/Pie.d.ts +62 -0
  198. package/dist/src/react/geoms/Pie.js +59 -0
  199. package/dist/src/react/geoms/Points.d.ts +84 -0
  200. package/dist/src/react/geoms/Points.js +207 -0
  201. package/dist/src/react/geoms/Points3d.d.ts +49 -0
  202. package/dist/src/react/geoms/Points3d.js +58 -0
  203. package/dist/src/react/geoms/Radar.d.ts +39 -0
  204. package/dist/src/react/geoms/Radar.js +59 -0
  205. package/dist/src/react/geoms/Range.d.ts +31 -0
  206. package/dist/src/react/geoms/Range.js +20 -0
  207. package/dist/src/react/geoms/RingStack.d.ts +39 -0
  208. package/dist/src/react/geoms/RingStack.js +65 -0
  209. package/dist/src/react/geoms/Rule.d.ts +29 -0
  210. package/dist/src/react/geoms/Rule.js +51 -0
  211. package/dist/src/react/geoms/Sankey.d.ts +24 -0
  212. package/dist/src/react/geoms/Sankey.js +51 -0
  213. package/dist/src/react/geoms/Segment.d.ts +36 -0
  214. package/dist/src/react/geoms/Segment.js +39 -0
  215. package/dist/src/react/geoms/Sunburst.d.ts +46 -0
  216. package/dist/src/react/geoms/Sunburst.js +64 -0
  217. package/dist/src/react/geoms/Surface.d.ts +32 -0
  218. package/dist/src/react/geoms/Surface.js +49 -0
  219. package/dist/src/react/geoms/Text.d.ts +35 -0
  220. package/dist/src/react/geoms/Text.js +40 -0
  221. package/dist/src/react/geoms/Treemap.d.ts +39 -0
  222. package/dist/src/react/geoms/Treemap.js +16 -0
  223. package/dist/src/react/geoms/Violin.d.ts +56 -0
  224. package/dist/src/react/geoms/Violin.js +60 -0
  225. package/dist/src/react/geoms/Volume.d.ts +37 -0
  226. package/dist/src/react/geoms/Volume.js +40 -0
  227. package/dist/src/react/geoms/Waterfall.d.ts +43 -0
  228. package/dist/src/react/geoms/Waterfall.js +18 -0
  229. package/dist/src/react/geoms/cube-stage.d.ts +39 -0
  230. package/dist/src/react/geoms/cube-stage.js +85 -0
  231. package/dist/src/react/geoms/hierarchy-cells.d.ts +42 -0
  232. package/dist/src/react/geoms/hierarchy-cells.js +59 -0
  233. package/dist/src/react/geoms/sector-axis.d.ts +66 -0
  234. package/dist/src/react/geoms/sector-axis.js +99 -0
  235. package/dist/src/react/gl/GlMesh.d.ts +22 -0
  236. package/dist/src/react/gl/GlMesh.js +78 -0
  237. package/dist/src/react/gl/GlPoints.d.ts +45 -0
  238. package/dist/src/react/gl/GlPoints.js +117 -0
  239. package/dist/src/react/gl/GlVolume.d.ts +28 -0
  240. package/dist/src/react/gl/GlVolume.js +112 -0
  241. package/dist/src/react/gl/GlWalls.d.ts +24 -0
  242. package/dist/src/react/gl/GlWalls.js +55 -0
  243. package/dist/src/react/gl/context.d.ts +71 -0
  244. package/dist/src/react/gl/context.js +98 -0
  245. package/dist/src/react/gl/encode.d.ts +120 -0
  246. package/dist/src/react/gl/encode.js +215 -0
  247. package/dist/src/react/gl/index.d.ts +10 -0
  248. package/dist/src/react/gl/index.js +8 -0
  249. package/dist/src/react/gl/refresh.d.ts +7 -0
  250. package/dist/src/react/gl/refresh.js +19 -0
  251. package/dist/src/react/gl/renderer.d.ts +377 -0
  252. package/dist/src/react/gl/renderer.js +1081 -0
  253. package/dist/src/react/gl/shaders.d.ts +92 -0
  254. package/dist/src/react/gl/shaders.js +405 -0
  255. package/dist/src/react/gl/surface.d.ts +31 -0
  256. package/dist/src/react/gl/surface.js +73 -0
  257. package/dist/src/react/index.d.ts +12 -0
  258. package/dist/src/react/index.js +11 -0
  259. package/dist/src/react/orbit.d.ts +38 -0
  260. package/dist/src/react/orbit.js +81 -0
  261. package/dist/src/react/sides/DendrogramPanel.d.ts +32 -0
  262. package/dist/src/react/sides/DendrogramPanel.js +39 -0
  263. package/dist/src/react/sides/DensityPanel.d.ts +31 -0
  264. package/dist/src/react/sides/DensityPanel.js +37 -0
  265. package/dist/src/react/sides/HistogramPanel.d.ts +30 -0
  266. package/dist/src/react/sides/HistogramPanel.js +18 -0
  267. package/dist/src/react/sides/RugPanel.d.ts +28 -0
  268. package/dist/src/react/sides/RugPanel.js +21 -0
  269. package/dist/src/react/sides/TrackPanel.d.ts +37 -0
  270. package/dist/src/react/sides/TrackPanel.js +27 -0
  271. package/dist/src/react/theme.d.ts +48 -0
  272. package/dist/src/react/theme.js +148 -0
  273. package/dist/src/react/useFits.d.ts +26 -0
  274. package/dist/src/react/useFits.js +62 -0
  275. package/dist/src/react/useZoom.d.ts +50 -0
  276. package/dist/src/react/useZoom.js +141 -0
  277. package/package.json +164 -5
  278. package/theme/default.css +62 -0
package/README.md CHANGED
@@ -1,3 +1,2172 @@
1
- # Temporary Holding Version
1
+ # ts-lib-viz <!-- omit in toc -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## Version <!-- omit in toc -->
4
+
5
+ v0.1.4
6
+
7
+ ## Table of Contents <!-- omit in toc -->
8
+
9
+ - [Summary](#summary)
10
+ - [Install](#install)
11
+ - [Quick start](#quick-start)
12
+ - [Layers and kinds](#layers-and-kinds)
13
+ - [Point](#point)
14
+ - [Line](#line)
15
+ - [Area](#area)
16
+ - [Ribbon](#ribbon)
17
+ - [Errorbar, linerange, pointrange and crossbar](#errorbar-linerange-pointrange-and-crossbar)
18
+ - [Segment](#segment)
19
+ - [Bar](#bar)
20
+ - [Waterfall](#waterfall)
21
+ - [Histogram](#histogram)
22
+ - [Frequency polygon](#frequency-polygon)
23
+ - [Density](#density)
24
+ - [Hex](#hex)
25
+ - [Boxplot](#boxplot)
26
+ - [Violin](#violin)
27
+ - [Flip](#flip)
28
+ - [Parallel coordinates](#parallel-coordinates)
29
+ - [Heatmap](#heatmap)
30
+ - [Contour](#contour)
31
+ - [The polar three](#the-polar-three)
32
+ - [Hierarchies](#hierarchies)
33
+ - [Flows](#flows)
34
+ - [Genome](#genome)
35
+ - [Aesthetics: columns through `aes`, constants flat](#aesthetics-columns-through-aes-constants-flat)
36
+ - [Size and shape](#size-and-shape)
37
+ - [Positions](#positions)
38
+ - [The cube: three position scales](#the-cube-three-position-scales)
39
+ - [Scales, `labs` and guides](#scales-labs-and-guides)
40
+ - [Facets](#facets)
41
+ - [Sizing: three ways to set it](#sizing-three-ways-to-set-it)
42
+ - [Side panels: four things beside the geoms](#side-panels-four-things-beside-the-geoms)
43
+ - [Naming things: numbers, direct labels and categories](#naming-things-numbers-direct-labels-and-categories)
44
+ - [`Viz`: drawing from a spec](#viz-drawing-from-a-spec)
45
+ - [`plot()`: the builder](#plot-the-builder)
46
+ - [The layer methods](#the-layer-methods)
47
+ - [The chart methods](#the-chart-methods)
48
+ - [A persistent chain](#a-persistent-chain)
49
+ - [`spec()` and `props()`](#spec-and-props)
50
+ - [Selection: `onSelect` and `keyField`](#selection-onselect-and-keyfield)
51
+ - [Zoom: the reader's own window](#zoom-the-readers-own-window)
52
+ - [Brush: a box or a lasso over a scatter](#brush-a-box-or-a-lasso-over-a-scatter)
53
+ - [Toolbar: the reader's controls](#toolbar-the-readers-controls)
54
+ - [Out of bounds: readings a scale drops](#out-of-bounds-readings-a-scale-drops)
55
+ - [Reference lines: `hline`, `vline` and `abline`](#reference-lines-hline-vline-and-abline)
56
+ - [Text and annotations](#text-and-annotations)
57
+ - [Fits: the service boundary](#fits-the-service-boundary)
58
+ - [`PredictionBand` to `Fit`](#predictionband-to-fit)
59
+ - [Smooth and fit: two spec shapes](#smooth-and-fit-two-spec-shapes)
60
+ - [Data: three shapes, one path](#data-three-shapes-one-path)
61
+ - [Color](#color)
62
+ - [Diverging maps take a center](#diverging-maps-take-a-center)
63
+ - [Theme](#theme)
64
+ - [The critic](#the-critic)
65
+ - [Footer counts](#footer-counts)
66
+ - [Saved specs: `StoredSpec`, `loadSpec` and `SPEC_VERSION`](#saved-specs-storedspec-loadspec-and-spec_version)
67
+ - [Profiles: the capability gate](#profiles-the-capability-gate)
68
+ - [Figure sets](#figure-sets)
69
+ - [Export](#export)
70
+ - [Scale: the renderer switch thresholds](#scale-the-renderer-switch-thresholds)
71
+ - [`/builder`: the property column](#builder-the-property-column)
72
+ - [`/builder` host requirements](#builder-host-requirements)
73
+ - [`/graph`: the network surface](#graph-the-network-surface)
74
+ - [One canvas serves one layout](#one-canvas-serves-one-layout)
75
+ - [`/mcp`: the MCP server](#mcp-the-mcp-server)
76
+ - [Differences from ggplot2](#differences-from-ggplot2)
77
+ - [Migrating a saved spec](#migrating-a-saved-spec)
78
+ - [Export map and full API](#export-map-and-full-api)
79
+ - [Stability](#stability)
80
+ - [Design language](#design-language)
81
+ - [Contributing](#contributing)
82
+
83
+ ## Summary
84
+
85
+ A plotting package for scientific data in Tetra. Forty layer kinds under a ggplot2-style grammar, a WebGL tier that
86
+ draws millions of geoms, a property column that edits a chart, and a critic that checks each figure against the design
87
+ rules.
88
+
89
+ ## Install
90
+
91
+ ```bash
92
+ yarn add @tetrascience-npm/ts-lib-viz
93
+ ```
94
+
95
+ `react` and `react-dom` 18 or 19 are required peers. The other four peers are optional, and only the entry point that
96
+ imports one needs it. The package runs on Node 18 or later.
97
+
98
+ | Entry point | Contents | Peers it needs |
99
+ | ------------ | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
100
+ | `/core` | The builder, the spec, loading, the data adapters, the critic, profiles, palettes, tokens | none |
101
+ | `/react` | `Viz`, the toolbar's types, the GPU provider, export and the theme hooks | `react`, `react-dom` |
102
+ | `/builder` | `PlotPanel`, the property column | `@tetrascience-npm/tetrascience-react-ui` ^1.0.0 and `lucide-react` ^0.577.0 or ^1.0.0, optional |
103
+ | `/graph` | `GraphSurface`, a force-directed network on the package's own context | `@cosmos.gl/graph` ^3.3.0 and `@luma.gl/webgl` ~9.3.6, optional |
104
+ | `/mcp` | The MCP tool catalog and headless drawing to SVG and PNG. Node only | none. `@modelcontextprotocol/sdk` and `@resvg/resvg-js` are dependencies and install with the package |
105
+ | `/theme.css` | The twelve `--viz-*` token values, light and dark | none |
106
+
107
+ The `ts-lib-viz-mcp` bin serves the MCP tools over stdio. Aggregation runs on your service. Send the result back as
108
+ rows, columns or an Arrow table and `toPlotData` reads it.
109
+
110
+ ## Quick start
111
+
112
+ ```tsx
113
+ import {plot} from "@tetrascience-npm/ts-lib-viz/core";
114
+ import {Viz} from "@tetrascience-npm/ts-lib-viz/react";
115
+ import "@tetrascience-npm/ts-lib-viz/theme.css";
116
+
117
+ const rows = [
118
+ {lot: "LOT-1", plate: "P1", kd: 4.2, tm: 63.1},
119
+ {lot: "LOT-2", plate: "P1", kd: 18.7, tm: 55.4},
120
+ // ...
121
+ ];
122
+
123
+ <Viz
124
+ {...plot(rows, {x: "kd", y: "tm"})
125
+ .point()
126
+ .labs({headline: "The second cluster trades stability for affinity", caption: "synthetic campaign"})
127
+ .props()}
128
+ fieldOverrides={{kd: {label: "KD", unit: "nM"}, tm: {label: "Tm", unit: "°C"}}}
129
+ />;
130
+ ```
131
+
132
+ <img src="docs/images/point.svg" width="520" alt="Points of KD against Tm showing two clusters">
133
+
134
+ `plot(data, aes)` starts a chart and maps columns to aesthetics, ggplot's `aes()`. Each layer method adds a layer,
135
+ `labs()` writes the words, and `props()` hands `Viz` the `ChartSpec` beside the rows. `spec()` returns the document
136
+ alone, for a store.
137
+
138
+ Write the `headline` as the claim the chart makes. Rule 10 of the design language asks for one, and the save gate
139
+ refuses a figure without it. Type size and spacing come off the panel width.
140
+
141
+ ## Layers and kinds
142
+
143
+ `KINDS` lists the forty layer kinds. The kind, its builder method and the MCP layer kind are one name, and it is
144
+ ggplot2's name where ggplot2 has the layer.
145
+
146
+ | Group | Kinds |
147
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
148
+ | Cartesian | `point`, `line`, `area`, `ribbon`, `errorbar`, `linerange`, `pointrange`, `crossbar`, `segment`, `smooth`, `bar`, `waterfall`, `histogram`, `freqpoly`, `hex`, `boxplot`, `violin`, `density`, `heatmap`, `contour` |
149
+ | Reference and text | `hline`, `vline`, `abline`, `text`, `label` |
150
+ | Polar | `pie`, `gauge`, `radar` |
151
+ | Hierarchies | `treemap`, `icicle`, `sunburst` |
152
+ | Flows | `sankey`, `chord` |
153
+ | Genome | `ideogram` |
154
+ | Parallel | `parcoords` |
155
+ | In a cube | `point3d`, `surface`, `mesh3d`, `isosurface`, `volume` |
156
+
157
+ Chain layer methods over one `plot()` to layer them. A bar with a line on top is two calls on one chain. `fit()` writes
158
+ a `point` layer with a model on it, and `smooth()` draws the curve a `Fitter` returns.
159
+
160
+ The typed `layer(kind, options)` adds a layer when the kind is a variable. A literal kind takes the options its own
161
+ method takes, and a kind typed `PlotKind` takes each kind's fields at once, `AnyLayerOptions`:
162
+
163
+ ```ts
164
+ plot(rows, {x: "plate", y: "kd"}).layer("bar", {aggregate: "mean"}); // the same layer as .bar({aggregate: "mean"})
165
+ ```
166
+
167
+ Each kind runs ggplot's statistic under ggplot's name. `summary` reduces each group, by the layer's `aggregate` where
168
+ the kind takes one, under a bar, an area, a waterfall, a heatmap, the hierarchies, a pie, a gauge, the flows and a
169
+ surface. `bin` and `count` run under a histogram and a frequency polygon, `bin2d` under a hex and a surface, `boxplot`
170
+ under a boxplot, `boxplot` and `ydensity` under a violin, `density` under a density, `density2d` under a contour, and
171
+ `flow` under a sankey. An `aggregate` is `count`, `mean`, `median`, `min`, `max`, `sum` or `p95`. A statistic's
172
+ parameters are flat options on the layer method and land on `LayerSpec.statParams`.
173
+
174
+ `node docs/figures.mjs`, after a build, renders the figures below through the same `Viz` a consumer calls. The data is a
175
+ synthetic campaign with two clusters drawn from a normal distribution.
176
+
177
+ ### Point
178
+
179
+ ```tsx
180
+ <Viz
181
+ {...plot(rows, {x: "kd", y: "tm", color: "yield"}).point().labs({headline: "…"}).props()}
182
+ fieldOverrides={FIELDS}
183
+ />
184
+ ```
185
+
186
+ <img src="docs/images/point-color.svg" width="520" alt="Points colored by yield">
187
+
188
+ `color` on a numeric column takes the sequential map. On a text column it takes the categorical one.
189
+
190
+ A point larger than four pixels draws a one-pixel `halo` in the paper color, which keeps overlapping geoms countable.
191
+ The figures on this page print at half width and state `halo: 0`:
192
+
193
+ ```tsx
194
+ .point({halo: 0}) // no ring
195
+ .point({halo: 2, size: 6}) // a wider ring on larger geoms
196
+ ```
197
+
198
+ A point also takes `shape` (`circle`, `square`, `triangle`, `diamond`), `hollow` to draw that shape as an outline,
199
+ `alpha`, and `sizeRange` for the size aesthetic. `directLabels` names the notable few, and `fit` hangs a model on the
200
+ layer.
201
+
202
+ ### Line
203
+
204
+ ```tsx
205
+ <Viz
206
+ {...plot(rows, {x: "day", y: "yield"})
207
+ .line({aggregate: "mean"})
208
+ .labs({headline: "…"})
209
+ .scales({x: {kind: "band"}})
210
+ .props()}
211
+ fieldOverrides={FIELDS}
212
+ />
213
+ ```
214
+
215
+ <img src="docs/images/line.svg" width="520" alt="Mean yield rising across twelve days">
216
+
217
+ `aggregate` applies where x runs on bands. On a continuous scale the records draw as they are.
218
+
219
+ `group` cuts one path per value and leaves the color and the linetype to their own aesthetics, ggplot's
220
+ `aes(group =)`:
221
+
222
+ ```ts
223
+ plot(rows, {x: "time", y: "conc"})
224
+ .line({aes: {group: "subject", color: "treatment", linetype: "study"}})
225
+ .point({aes: {color: "treatment"}});
226
+ ```
227
+
228
+ Each subject's path takes its treatment's color and its study's linetype, read off its own rows. The legend names the
229
+ treatments and the studies. With no `group`, a color and a linetype on separate columns cut one path per pair, which
230
+ is ggplot's default group. A missing reading breaks the line, as it does in ggplot's `geom_path`. `step` takes `after`
231
+ or `before` and draws the readings as a staircase.
232
+
233
+ ### Area
234
+
235
+ ```tsx
236
+ <Viz
237
+ {...plot(rows, {x: "day", y: "yield"})
238
+ .area({aggregate: "mean"})
239
+ .labs({headline: "…"})
240
+ .scales({x: {kind: "band"}})
241
+ .props()}
242
+ fieldOverrides={FIELDS}
243
+ />
244
+ ```
245
+
246
+ <img src="docs/images/area.svg" width="520" alt="Mean yield across twelve days with the ground filled">
247
+
248
+ A line with the ground under it filled. The fill turns the trend into a quantity. The vertical scale starts at zero,
249
+ per rule 11. The edge draws over the fill to keep two adjacent washes apart. Groups on `fill` or `group` stack unless
250
+ the layer states a `position`.
251
+
252
+ ### Ribbon
253
+
254
+ ```tsx
255
+ <Viz
256
+ {...plot(daily, {x: "day"})
257
+ .ribbon({aes: {ymin: "lo", ymax: "hi", y: "mean"}})
258
+ .labs({headline: "…"})
259
+ .props()}
260
+ fieldOverrides={FIELDS}
261
+ />
262
+ ```
263
+
264
+ <img src="docs/images/ribbon.svg" width="520" alt="Mean yield across twelve days inside a band a standard deviation wide">
265
+
266
+ A band between two bound columns. `ymin` and `ymax` are the bounds and `y` is the estimate through them, and the
267
+ figure draws the interval your analysis produced. Omit `y` to draw the band alone. Under a plot aes that binds `y`,
268
+ the ribbon reads that column as its estimate.
269
+
270
+ Use a ribbon for an interval somebody else computed: a confidence band from a service, a spec limit, a tolerance. A
271
+ `fit` draws the band around a curve your `Fitter` returns.
272
+
273
+ ### Errorbar, linerange, pointrange and crossbar
274
+
275
+ ```tsx
276
+ <Viz {...plot(doses, {x: "dose", y: "mean", ymin: "lo", ymax: "hi"}).pointrange().labs({headline: "…"}).props()} />
277
+ ```
278
+
279
+ The ribbon's bounds drawn as one mark per reading, ggplot's four interval geoms. `errorbar` caps each end,
280
+ `linerange` draws the rule alone, `pointrange` marks the estimate on the rule, and `crossbar` draws a box with the
281
+ estimate across it. Use a ribbon for a continuous run and marks for readings taken apart, like six doses measured
282
+ separately.
283
+
284
+ `errorbar` and `crossbar` take `thickness`, the cap's reach and the box's width in pixels. `crossbar` takes a `fill`
285
+ for the box. The vertical axis starts at the lowest bound, because the length of each mark is the width of an
286
+ interval.
287
+
288
+ ### Segment
289
+
290
+ ```tsx
291
+ <Viz
292
+ {...plot(drift, {x: "day", y: "yield"})
293
+ .segment({aes: {xend: "dayEnd", yend: "yieldEnd", color: "plate"}})
294
+ .labs({headline: "…"})
295
+ .props()}
296
+ fieldOverrides={FIELDS}
297
+ />
298
+ ```
299
+
300
+ <img src="docs/images/segment.svg" width="520" alt="Each plate's mean yield from the first day of the run to the last">
301
+
302
+ One run per record, from where a reading started to where it finished. `x` and `y` are the start, and `xend` and
303
+ `yend` are the finish. Before-and-after pairs and drift vectors share this geometry.
304
+
305
+ Each record draws on its own, which is the split from `line`. Use a line where the readings form a sequence and a
306
+ segment where each pair stands alone. A segment draws a head at its finish, and `arrow: false` leaves it off for a
307
+ range with no start, such as a dumbbell.
308
+
309
+ ### Bar
310
+
311
+ ```tsx
312
+ <Viz
313
+ {...plot(rows, {x: "plate", y: "kd"}).bar({aggregate: "mean"}).labs({headline: "…"}).props()}
314
+ fieldOverrides={FIELDS}
315
+ />
316
+ ```
317
+
318
+ <img src="docs/images/bar.svg" width="520" alt="Mean KD per plate">
319
+
320
+ Bars encode by length. The axis anchors at zero and the critic blocks a log scale under them. Omit `y` for a count.
321
+ A bar over a numeric x draws one bar per distinct reading, as `geom_bar` and `geom_col` do, and its width is the
322
+ smallest gap between readings. To bin the readings, use a histogram.
323
+
324
+ `error: "sd"` draws the spread of the readings and `error: "sem"` draws how well their mean is pinned down. The footer
325
+ line states which one you asked for. Whiskers need two readings in a group. The vertical scale reaches the top of the
326
+ interval, keeping caps clear of the frame. An `area` takes the same option.
327
+
328
+ <img src="docs/images/spread.svg" width="520" alt="Mean affinity per plate with a standard deviation whisker and the four readings behind each bar">
329
+
330
+ `replicates: true` draws the readings themselves over the bars, for a reader counting what the mean was taken over.
331
+ Use it where x is a category. Past forty readings the dots overlap into one column of ink. A group that big shows
332
+ the bar alone, and the footer line records how many did.
333
+
334
+ ### Waterfall
335
+
336
+ ```tsx
337
+ <Viz
338
+ {...plot(steps, {x: "step", y: "change"}).waterfall({aggregate: "sum"}).labs({headline: "…"}).props()}
339
+ fieldOverrides={FIELDS}
340
+ />
341
+ ```
342
+
343
+ Signed steps on a running total. Each step starts where the previous one finished. The geom draws a connector between
344
+ them and paints rises and falls apart, and `parts` takes a paint for `rise`, `fall` and `connector`.
345
+
346
+ A step's length is the size of the move and the total it lands on reads up from zero. The vertical axis starts there.
347
+ Negative steps run back down over the previous step, which is the point of the kind.
348
+
349
+ ### Histogram
350
+
351
+ ```tsx
352
+ <Viz {...plot(rows, {x: "kd"}).histogram().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
353
+ ```
354
+
355
+ <img src="docs/images/histogram.svg" width="520" alt="Distribution of KD showing two populations">
356
+
357
+ A histogram bins `x` and counts under each bin. A layer stating neither `binwidth` nor `bins` takes the
358
+ Freedman-Diaconis width off the data. `aggregate` is off its options and fails to compile.
359
+
360
+ The layer takes `stat_bin`'s parameters flat. `binwidth` is the width in the column's own units, and `bins` is a count
361
+ of intervals across the range. `boundary` names an edge and `center` names the middle of an interval, and either one
362
+ fixes where all the edges fall. Pass one of the two. `closed` takes `right`, the default, or `left`, and decides which
363
+ interval a reading on an edge counts in. `breaks` takes the edges themselves. `pad` adds an empty interval
364
+ at each end. `dropEmpty` takes `none`, `all` or `extremes` and says which empty intervals survive, which is
365
+ `stat_bin`'s `drop` renamed apart from the violin's boolean.
366
+
367
+ ```tsx
368
+ plot(rows, {x: "kd"}).histogram({binwidth: 1, boundary: 0, closed: "left"});
369
+ ```
370
+
371
+ A width on its own puts the first edge half a width below the lowest reading. Add `boundary: 0` to break a count per
372
+ whole unit on whole units. An alignment on its own keeps the automatic width. `{boundary: 0}` shifts the edges of a
373
+ Freedman-Diaconis binning and leaves the width to the data.
374
+
375
+ The arithmetic is ported from ggplot2 4.0.2 and pinned against `ggplot_build` in `test/core/binning-parity.test.ts`.
376
+ An area over a continuous x takes the same parameters.
377
+
378
+ ### Frequency polygon
379
+
380
+ ```tsx
381
+ <Viz {...plot(iris, {x: "Petal.Length", color: "Species"}).freqpoly({binwidth: 0.4}).props()} fieldOverrides={FIELDS} />
382
+ ```
383
+
384
+ The histogram's counts drawn as a line through the interval midpoints, one line per color, linetype or group. Two
385
+ lines cross in the open, which makes this the shape for comparing distributions over one axis. `step` takes `before`
386
+ or `after` and draws the counts as a staircase, keeping the flat top each bin has. It takes the histogram's binning
387
+ parameters.
388
+
389
+ ### Density
390
+
391
+ ```tsx
392
+ <Viz {...plot(rows, {x: "waiting"}).density({bw: 2, kernel: "epanechnikov"}).props()} fieldOverrides={FIELDS} />
393
+ ```
394
+
395
+ A kernel density estimate, one curve per value of the layer's `color`, `fill` or `group`. `bw` is the bandwidth in the
396
+ column's own units, or a rule that reads one off the data: `nrd0`, Silverman's and the default, or `nrd`, Scott's.
397
+ `adjust` multiplies whatever bandwidth was chosen, and `n` sets how many points the curve is evaluated at. `kernel`
398
+ picks the shape: `gaussian`, the default, `epanechnikov`, `rectangular`, `triangular`, `biweight`, `cosine` or
399
+ `optcosine`. `trim` and `bounds` keep the curve inside a range.
400
+
401
+ Bandwidth changes the answer. Four curves over one column can each be honest and each support a different reading.
402
+ State the bandwidth behind each. Two layers smoothed at different bandwidths on one frame draw `bandwidths-disagree`.
403
+
404
+ ### Hex
405
+
406
+ ```tsx
407
+ <Viz {...plot(rows, {x: "kd", y: "tm"}).hex().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
408
+ ```
409
+
410
+ <img src="docs/images/hex.svg" width="520" alt="Two-dimensional density of KD against Tm on hexagons">
411
+
412
+ A count over a lattice of cells, ggplot's `geom_hex`. `tiling` picks the lattice and draws hexagons unless it says
413
+ `rect`, which stands in for `geom_bin_2d`. The count paints the cell through the fill scale.
414
+
415
+ The layer takes `stat_bin_2d`'s parameters, each one a number or a pair of numbers, across then down. `binwidth` is the
416
+ size of a cell in the data's own units and `bins` is how many cells span each axis, 30 by default. `boundary` and
417
+ `center` align them, at zero by default. A cell of price starts at zero dollars. `closed` decides the inclusive end and
418
+ defaults to the right one. `drop: false` draws each cell of the lattice, putting a count of zero at the bottom of the
419
+ map.
420
+
421
+ ```tsx
422
+ plot(rows, {x: "carat", y: "price"}).hex({bins: 20, tiling: "rect"});
423
+ ```
424
+
425
+ ### Boxplot
426
+
427
+ ```tsx
428
+ <Viz {...plot(rows, {x: "plate", y: "tm"}).boxplot().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
429
+ ```
430
+
431
+ <img src="docs/images/boxplot.svg" width="520" alt="Tm distribution per plate as boxes and whiskers">
432
+
433
+ `coef` sets how far a whisker reaches past the quartiles, in interquartile ranges, 1.5 by default, and `quantileType`
434
+ picks one of R's nine quantile definitions, 7 by default. `parts` paints the `box`, `whisker`, `staple`, `median` and
435
+ `outlier` on their own:
436
+
437
+ ```tsx
438
+ .boxplot({parts: {whisker: {linewidth: 0.8}, outlier: {shape: "diamond", size: 3}}})
439
+ ```
440
+
441
+ ### Violin
442
+
443
+ ```tsx
444
+ <Viz {...plot(rows, {x: "plate", y: "tm"}).violin().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
445
+ ```
446
+
447
+ <img src="docs/images/violin.svg" width="520" alt="Tm density per plate, mirrored around each band">
448
+
449
+ The boxplot's aesthetics, showing the shape behind the quartiles. Two distributions can share one pair of quartiles
450
+ while one of them is bimodal. The median tick comes along for reading the pair together.
451
+
452
+ `scale` says what stays constant across the bands. `area` gives each violin the same area, `count` scales area by the
453
+ number of readings, and `width` gives each the same width. Equal widths compare shape alone, and `width` draws
454
+ `width-hides-the-count`. `half` takes `both`, `high` or `low`, and one half is a raincloud's, leaving room for a box.
455
+ `quantiles` takes a list of fractions and rules them across the shape, and `coef` sets the whisker reach as the
456
+ boxplot does.
457
+
458
+ ### Flip
459
+
460
+ ```tsx
461
+ <Viz
462
+ {...plot(lots, {x: "lot", y: "titer"}).bar({aggregate: "mean"}).labs({headline: "…"}).flip().props()}
463
+ fieldOverrides={FIELDS}
464
+ />
465
+ ```
466
+
467
+ <img src="docs/images/flip.svg" width="520" alt="Mean titer per purification lot, the lot names read down the left side">
468
+
469
+ `flip()` writes `coord: "flip"`, ggplot's `coord_flip()`, which puts the aesthetic bound to x up the side and the
470
+ measure across. Thirty lot names read straight across in this orientation, and the left margin measures off the
471
+ longest one and grows to fit it.
472
+
473
+ The names stay with the data. `x` is still the category, `scales.x` still configures it, and an `hline` still marks
474
+ the measure. The swap happens once, where the frame hands its two axes to the renderer. The critic reads the spec, and
475
+ a bar on a log measure axis is `scales.y.transform` either way round.
476
+
477
+ Bars, boxplots and violins draw flipped. Parallel plots and the cube kinds read the flag and draw as they were.
478
+
479
+ ### Parallel coordinates
480
+
481
+ ```tsx
482
+ <Viz
483
+ {...plot(rows, {dimensions: ["kd", "tm", "yield"]})
484
+ .parcoords()
485
+ .labs({headline: "…"})
486
+ .props()}
487
+ fieldOverrides={FIELDS}
488
+ />
489
+ ```
490
+
491
+ <img src="docs/images/parcoords.svg" width="520" alt="Three vertical rules, one per measure, with a line per lot crossing them">
492
+
493
+ Four or more measures at once. `dimensions` names them, two at the least and three on a radar, and each rule has its
494
+ own units and its own scale. Past eight measures the footer counts the rest.
495
+
496
+ Drag on a rule to keep a range. Records outside it drop from all the rules at once. The crossing pattern left behind
497
+ belongs to the candidates still in play, and the footer line counts what survived. A second range narrows what the
498
+ first left.
499
+
500
+ ### Heatmap
501
+
502
+ ```tsx
503
+ <Viz
504
+ {...plot(rows, {x: "day", y: "plate", z: "yield"})
505
+ .heatmap({aggregate: "mean"})
506
+ .labs({headline: "…"})
507
+ .scales({x: {kind: "band"}})
508
+ .props()}
509
+ fieldOverrides={FIELDS}
510
+ />
511
+ ```
512
+
513
+ <img src="docs/images/heatmap.svg" width="520" alt="Mean yield by day and plate as a color grid">
514
+
515
+ The one geom that reads a category on both axes. `z` is the measure the cells reduce, and omitting it gives counts.
516
+ The map reads the fill scale, `scales.fill`. `cellGap`, `cornerRadius`, `fadeBySupport` and `emptyAsZero` shape the
517
+ cells, and `dimensions` turns the grid into a gate grid of measures against their cuts.
518
+
519
+ ### Contour
520
+
521
+ ```tsx
522
+ <Viz {...plot(rows, {x: "kd", y: "tm"}).contour().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
523
+ ```
524
+
525
+ <img src="docs/images/contour.svg" width="520" alt="Density contours over two clusters">
526
+
527
+ Unbound, `z` leaves the statistic to estimate a density, and `adjust` multiplies its smoothing radius. With `z` bound,
528
+ the rows' own lattice cuts into bands.
529
+
530
+ ### The polar three
531
+
532
+ ```tsx
533
+ <Viz {...plot(diamonds, {x: "cut"}).pie({numbers: {format: "percent"}}).labs({headline: "…"}).props()} />
534
+ <Viz {...plot(cars, {x: "cyl"}).pie({innerRadius: 0.55}).labs({headline: "…"}).props()} />
535
+ <Viz {...plot(cars, {value: "mpg"}).gauge({aggregate: "mean", numbers: {}}).labs({headline: "…"}).props()} />
536
+ <Viz {...plot(three, {dimensions: ["hp", "disp", "wt", "mpg"], color: "model"}).radar().labs({headline: "…"}).props()} />
537
+ ```
538
+
539
+ Polar is the coordinate system of these kinds and of `sunburst`, `chord` and `ideogram`, and `ChartSpec.coord` takes
540
+ no polar value. Polar is allowed where the figure writes its numbers, and the critic checks four conditions. Set
541
+ `numbers` to write the values or `directLabels` to name the slices, or the ring draws `angle-encodes-comparison`. Keep
542
+ the slice count inside what the panel can label at its type size, or it draws `slices-past-legible` with the number
543
+ that fits. Give a dial its `numbers`, or it draws `single-value-as-arc`. Reduce with something additive. Slices claim
544
+ to be parts of one whole, and anything else draws `pie-not-parts` and blocks the save.
545
+
546
+ A donut is a pie with `innerRadius` above zero. A gauge reads one `value` and takes `scales.y.limits` for the ends of
547
+ its sweep, with `sweep`, `radius` and `sections` shaping the dial. A radar draws one polygon per record and takes its
548
+ measures through `dimensions`, in the order you write them.
549
+
550
+ ### Hierarchies
551
+
552
+ ```tsx
553
+ <Viz {...plot(rows, {label: "label", value: "value", parent: "parent"}).treemap().props()} fieldOverrides={FIELDS} />
554
+ <Viz {...plot(rows, {label: "label", value: "value", parent: "parent"}).icicle().props()} fieldOverrides={FIELDS} />
555
+ <Viz {...plot(rows, {label: "label", value: "value", parent: "parent"}).sunburst().props()} fieldOverrides={FIELDS} />
556
+ ```
557
+
558
+ Three arrangements over one hierarchy, reading the same three aesthetics. `label` names a node, `value` is its
559
+ magnitude, and `parent` is the node above it. A treemap packs rectangles. An icicle gives each level a row of its own,
560
+ and a sunburst wraps that layout round a center.
561
+
562
+ Bind `parent` for the packing to have nesting to show. A flat treemap draws `area-with-no-nesting`, because lengths
563
+ compare better than areas.
564
+
565
+ ### Flows
566
+
567
+ ```tsx
568
+ plot(rows, {source: "from", target: "to", value: "n"}).sankey().labs({headline: "The funnel"});
569
+ plot(rows, {source: "from", target: "to", value: "n"}).chord({gap: 2, inset: 4}).labs({headline: "The traffic"});
570
+ ```
571
+
572
+ A sankey and a chord bind the same three aesthetics and read them differently. A sankey runs the flow along columns
573
+ and answers where the population went. `normalize: "column"` measures each column against its own population, and
574
+ `align: "justify"` puts each end node in the last column. A chord closes the flow into a circle, sizes a sector by
575
+ the flows touching its name, and answers which pairs exchange the most. `gap` separates one sector from the next, in
576
+ degrees, and `inset` pulls the ribbons off the band, in pixels.
577
+
578
+ ### Genome
579
+
580
+ ```tsx
581
+ plot(bands, {sector: "chrom", start: "start", end: "end", fill: "stain"})
582
+ .ideogram({numbers: {format: "auto"}, rotate: 90})
583
+ .labs({headline: "Human genome: Giemsa bands, hg38"});
584
+ ```
585
+
586
+ A genome round a circle, one sector per chromosome, from the real karyotype. `sector`, `start` and `end` place each
587
+ band in base pairs, and a stain column on `fill` paints through the Giemsa map. `rings` stacks readings of the same
588
+ rows outside the circle, and `links` draws a curve between two positions inside it. `rotate` turns the first sector,
589
+ in degrees counterclockwise from twelve, and `gap` separates the sectors.
590
+
591
+ ## Aesthetics: columns through `aes`, constants flat
592
+
593
+ Inside `aes` a name is a column, and outside it a name is a value, as in ggplot. `plot(data, aes)` sets the aes each
594
+ layer inherits. A layer's own `aes` option binds more columns or overrides one, and each flat option is a constant:
595
+
596
+ ```tsx
597
+ plot(rows, {x: "plate", y: "kd"})
598
+ .bar({aes: {fill: "lot"}, aggregate: "mean", color: "black", linewidth: 0.5, alpha: 0.8}) // fill from a column, three constants
599
+ .point({aes: {color: "lot"}, size: 3}); // this layer's own color column, and a constant size
600
+ ```
601
+
602
+ `Aes` keys are `Aesthetic` names. `plot()` refuses an unknown key at compile time, the British spelling of `color`
603
+ among them, and a layer throws on one at run time. A flat option the kind reads nowhere throws, naming the key.
604
+
605
+ `color` is the edge and the line, and `fill` is the interior, the split ggplot makes. A kind maps the one its own paint
606
+ is and takes the other as its outline or its interior constant:
607
+
608
+ | Aesthetic | Kinds |
609
+ | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
610
+ | `color` | `point`, `line`, `segment`, `smooth`, `freqpoly`, `density`, `errorbar`, `linerange`, `pointrange`, `crossbar`, `parcoords`, `radar`, `point3d`, `hline`, `vline`, `abline`, `text`, `label` |
611
+ | `fill` | `area`, `ribbon`, `bar`, `histogram`, `boxplot`, `violin`, `density`, `pie`, `ideogram`, `heatmap` |
612
+ | `size` | `point`, `point3d` |
613
+ | `shape`, `alpha` | `point` |
614
+ | `linetype` | `line`, `freqpoly`, `hline`, `vline`, `abline` |
615
+ | `group` | `point`, `line`, `area`, `ribbon`, the four interval kinds, `segment`, `smooth`, `freqpoly`, `density`, `text`, `label` |
616
+ | `ymin`, `ymax` | `ribbon` and the four interval kinds |
617
+ | `xend`, `yend` | `segment` |
618
+ | `z` | `heatmap`, `contour` and the cube |
619
+ | `dimensions` | `parcoords`, `radar`, and a `heatmap` gate grid |
620
+ | `label` | `text`, `label`, the reference lines and the hierarchies |
621
+ | `value` | the hierarchies, the flows, `gauge`, `isosurface`, `volume` |
622
+ | `parent` | the hierarchies |
623
+ | `source`, `target` | the flows |
624
+ | `sector`, `start`, `end` | `ideogram` |
625
+ | `faces` | `mesh3d` |
626
+ | `yintercept`, `xintercept`, `slope`, `intercept` | `hline`, `vline` and `abline` in turn |
627
+
628
+ The fill scale paints the cells of the `heatmap`, `hex` and `contour` kinds off the measure each one computes.
629
+
630
+ A heatmap that binds `fill` to a text column colors each cell by its rows' most common category, ggplot's
631
+ `geom_tile(aes(fill = residue))`. Its legend draws a swatch per category.
632
+
633
+ The flat constants are ggplot's names: `color`, `fill`, `alpha`, `linewidth` and `linetype`, with `size` and `shape`
634
+ on a point. Widths are in CSS pixels. ggplot's 0.75mm line unit needs a dpi figure that comes from the display.
635
+ `linetype` takes ggplot's six patterns: `solid`, `dashed`, `dotted`, `dotdash`, `longdash` and `twodash`.
636
+
637
+ `LayerStyle` has the constants on the spec, and the `geom-style` group of a capability profile gates it. A composite
638
+ geom takes paint on its parts through `parts`, keyed by the parts its kind has. A kind with no parts takes no `parts`
639
+ key.
640
+
641
+ ### Size and shape
642
+
643
+ ```tsx
644
+ <Viz
645
+ {...plot(rows, {x: "kd", y: "tm", color: "plate", size: "yield"}).point().labs({headline: "…"}).props()}
646
+ fieldOverrides={FIELDS}
647
+ />
648
+ ```
649
+
650
+ `size` maps on `point` and `point3d`, the two kinds with geoms to size. The scale is area-proportional: the value maps
651
+ onto area and the radius is its square root, which keeps the drawn area equal to the number it stands for. The radii
652
+ run from half the panel's own point radius to two and a half times it, and `sizeRange` overrides both ends.
653
+
654
+ A mapped aesthetic draws a legend for the scale to read back, and `size` draws two findings.
655
+ `size-carries-the-measure` fires where a position scale is open, because position compares better than area.
656
+ `size-past-fill-budget` fires where the resolved diameters fill the frame, and it reads the diameters alone.
657
+
658
+ `shape` is the other aesthetic a point takes. The package draws four glyphs, and a column with five or more values
659
+ draws `shapes-past-glyphs`.
660
+
661
+ ## Positions
662
+
663
+ `position` decides what happens where two geoms share a band. The adjustments are ggplot's:
664
+
665
+ | `position` | Effect |
666
+ | ----------------- | --------------------------------------------------------------------------------------------------------------------------- |
667
+ | `identity` | Each geom where its reading falls |
668
+ | `stack` | Each group on the running total of those before it. `offset: "silhouette"` centers it on zero, `wiggle` draws a streamgraph |
669
+ | `fill` | A stack divided by the band total, read as shares of one |
670
+ | `dodge`, `dodge2` | Each group in its own slot of the band. `width` is the fraction of the band the set takes |
671
+ | `jitter` | Each geom moved by up to `width` and `height` either way, in data units |
672
+ | `jitterdodge` | A slot per level of the layer's color, then a jitter inside it |
673
+ | `nudge` | Each geom moved by a fixed `x` and `y`, in the axes' own units |
674
+
675
+ <img src="docs/images/stack.svg" width="520" alt="Yield per day stacked by plate, one segment per plate in each day's band">
676
+
677
+ A bar, histogram or area layer whose groups draw several traces stacks them where it states no position, as
678
+ `geom_bar`, `geom_histogram` and `geom_area` do. A point and a line keep identity. A stack sets a floor under each geom
679
+ and keeps each group's trace whole, which keeps the legend, the color assignment and the hover working. A negative
680
+ reading stacks down from zero and a positive one up from it, each sign on its own running total, as `position_stack`
681
+ does. A streamgraph offset over a negative reading drops the adjustment, and the footer line records it.
682
+
683
+ A dodge's `preserve` takes `total`, the default, where each band divides by the groups in it, or `single`, which
684
+ keeps one width across the bands. A text layer under a dodge takes the slot of the bar it names.
685
+
686
+ A jitter's `width` and `height` default to 0.4 times the axis's resolution, its smallest gap between readings, and a
687
+ band axis has resolution 1. A jitterdodge spans `dodgeWidth`, 0.75 unless stated. Its width, stated or not, divides by
688
+ the color levels plus two, and its default height moves nothing. The offsets hash off the row, and one spec exports to
689
+ one picture each time. `seed` shifts the offsets.
690
+
691
+ ## The cube: three position scales
692
+
693
+ A third position scale is allowed on two conditions: the reader can rotate the view, and the chart shows depth cues.
694
+ Motion parallax makes the projection invertible. Rotation ships as part of the geom.
695
+
696
+ Five kinds use the cube, each a row in the grammar table, and a capability profile withholds them by name.
697
+
698
+ ```tsx
699
+ <Viz {...plot(rows, {x: "kd", y: "tm", z: "yield"}).point3d().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
700
+ <Viz
701
+ {...plot(rows, {x: "kd", y: "tm", z: "yield"})
702
+ .surface({aggregate: "mean"})
703
+ .labs({headline: "…"})
704
+ .props()}
705
+ fieldOverrides={FIELDS}
706
+ />
707
+ <Viz {...plot(vertices, {x: "x", y: "y", z: "z", faces: ["i", "j", "k"]}).mesh3d().labs({headline: "…"}).props()} />
708
+ <Viz {...plot(rows, {x: "kd", y: "tm", z: "yield"}).isosurface({isoLevel: 0.4}).labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
709
+ <Viz {...plot(rows, {x: "kd", y: "tm", z: "yield", value: "count"}).volume().labs({headline: "…"}).props()} fieldOverrides={FIELDS} />
710
+ ```
711
+
712
+ | Kind | Geoms drawn | Reduction |
713
+ | ------------ | ---------------------------------------- | --------------------------------------- |
714
+ | `point3d` | One geom per record on three scales | none |
715
+ | `surface` | A relief, triangulated and lit | a measure over a grid of two dimensions |
716
+ | `mesh3d` | Vertices and the faces over them | the rows are the geometry |
717
+ | `isosurface` | The shell where a field equals one value | rows onto a grid of three |
718
+ | `volume` | The field read through its whole depth | rows onto a grid of three |
719
+
720
+ Drag turns the cube, and a pinch or a Ctrl-wheel moves in. A plain wheel scrolls the page. Both depth cues ship with
721
+ the geoms. They scale with distance in the vertex program, and a cloud casts a copy of itself onto the floor of the
722
+ box, joined to each geom by a drop line under a few hundred geoms. The axes are the box's own edges drawn in
723
+ projection, with each scale written along the edge furthest from the reader, because two of the three are foreshortened
724
+ at any angle.
725
+
726
+ The grid draws solid on the three back walls at each scale's breaks, and a geom on a wall or in front of one hides it. `panes`
727
+ shades those walls the way matplotlib's panes do. `walls` fills the two upright walls, `all` adds the floor, and a cube
728
+ draws no pane unless asked.
729
+
730
+ A geom inside the box reads and selects the way a flat one does. Its hover card shows the third measure and lands at
731
+ the pixel the camera put the geom at. The click that ends a turn stays queued. Dragging across the cloud moves the
732
+ camera.
733
+
734
+ A relief encodes height on color as well as on position, which keeps a plateau visible under a light facing it. The
735
+ light is fixed in the world, and turning the figure moves it across the surface. `isoLevel` places an isosurface's
736
+ shell as a fraction of the field's range, half unless stated.
737
+
738
+ A file shows one angle, and `exportSvg` writes an admission into a copy of a cube. `critique(spec, {exported: true})`
739
+ reports `cube-copied-static` to the author handing it out.
740
+
741
+ What a cube costs, measured on the GPU's own clock: a million geoms matches the flat path's frame rate, and ten million
742
+ costs about a tenth more. A raymarched frame is priced by pixels times steps, and the shipped 160 steps read about
743
+ 2 ms. `demo/README.md` has both tables. The five draw on the shared canvas and a still image shows one angle. Turn one
744
+ in the demo app.
745
+
746
+ ## Scales, `labs` and guides
747
+
748
+ `scales` on the spec has one scale per aesthetic, ggplot's `scale_*` family: `x`, `y` and `y2` take a
749
+ `PositionScale`, `color` and `fill` take a `ColorScale`, and `size`, `shape`, `alpha` and `linetype` take a
750
+ `GuideScale`, whose one field is the guide's `title`. `labs()` writes the headline, the subtitle, the caption and each
751
+ aesthetic's title, and the title lands on `scales.<aesthetic>.title`:
752
+
753
+ ```ts
754
+ plot(compounds, {x: "observed", y: "predicted"})
755
+ .point()
756
+ .abline({label: "1:1"})
757
+ .labs({headline: "Predictions hold within 2-fold", x: "Observed CL", y: "Predicted CL"})
758
+ .scales({x: {transform: "log10", limits: [3, 300]}, y: {transform: "log10", limits: [3, 300]}})
759
+ .fixed();
760
+
761
+ plot(curve, {x: "dose", y: "inhibition"})
762
+ .point()
763
+ .scale("x", {transform: "log2", breaks: [0.5, 2, 8, 32], labels: {"32": "32 µM"}})
764
+ .scale("y", {expand: {mult: [0, 0.05]}, include: [0]});
765
+ ```
766
+
767
+ Two calls on one scale merge. `log("y")` followed by `scale("y", {title: "Tm"})` gives a scale with both, and
768
+ `labs({y: "Tm"})` writes that same title.
769
+
770
+ The position scale's arguments are ggplot's continuous-scale arguments:
771
+
772
+ | `PositionScale` | ggplot | Effect |
773
+ | --------------- | ------------------------------- | -------------------------------------------------------------------- |
774
+ | `transform` | `transform` | `log10`, `log2`, `sqrt` or `pseudo_log`. `log()` writes `log10` |
775
+ | `reverse` | `scale_x_reverse()` | Runs the axis high to low |
776
+ | `limits` | `limits` | The two ends the axis runs between, in data units |
777
+ | `oob` | `oob` | What a reading past the limits becomes. See the next section but one |
778
+ | `breaks` | `breaks` | The labeled ticks, those inside the domain. Over `breakWidth` |
779
+ | `minorBreaks` | `minor_breaks` | The unlabeled ticks |
780
+ | `labels` | `labels` | Tick text keyed by `String(value)`, as a band axis renames too |
781
+ | `expand` | `expand = expansion(mult, add)` | Room past the data, in transformed units, the low end first |
782
+ | `include` | `expand_limits()` | Values the domain reaches, drawn or not |
783
+
784
+ Beside them, `kind` picks `band` or `continuous`, `time` reads epoch milliseconds as dates, and `bandSize`, `order`,
785
+ `breakWidth`, `format` and `decimals` shape the ticks and the bands. `format` is `auto`, `fixed`, `scientific` or
786
+ `percent`. `grid`, `minorGrid`, `minorTicks`, `linewidth`, `tickLength`, `tickSide`, `tickAngle` (degrees
787
+ counterclockwise, as ggplot's `element_text(angle)`), `titleAlign`, `fontSize` and `ink` are the axis chrome.
788
+
789
+ `order` on a band axis is a `BandOrder`. `{kind: "list", values, gaps}` writes the categories in the order given,
790
+ skips a value the data lacks, and breaks the band before each index in `gaps`. `{kind: "cluster"}` orders them by
791
+ hierarchical clustering at pheatmap's defaults. Its `distance` is `euclidean`, the default, or `correlation`, and
792
+ its `method` is `complete`, the default, `single`, `average`, `weighted` or `ward`. `cut` breaks the band between
793
+ that many clusters, and `kmeans` reduces the rows to that many centroids before the tree is built.
794
+
795
+ A time axis ticks on the UTC calendar by default. A saved figure then draws the same in any zone. `timezone: "local"`
796
+ ticks on the reader's own clock, and the hover card writes its times on that clock too.
797
+
798
+ A transform decides the statistic's space too. A histogram along a `sqrt` axis bins in root space, and a marginal
799
+ panel bins the way its axis runs. `log2` spaces a two-fold dilution evenly and ticks at powers of two. `sqrt` drops a
800
+ reading below zero and the footer counts it. `pseudo_log` is d3's symlog: linear inside one unit of zero, logarithmic
801
+ past it, for readings of both signs, with ticks at the signed decades.
802
+
803
+ Absent, `expand` is a twentieth of the span each end, and a log axis takes a fifth past each end. A grounded axis
804
+ starts at zero. Stated `limits` are the domain as written and take no expansion.
805
+
806
+ `fixed(ratio)` is `coord_fixed`: `ratio` units of y per unit of x on screen, in transformed space. The panel's height
807
+ follows from its width and the two domains, over `height` and `aspect`. At one, on matching axes, the unit line runs
808
+ at 45 degrees and a 2-fold band reads the same width each side.
809
+
810
+ A layer reads the second vertical scale with `axis: "y2"`:
811
+
812
+ ```tsx
813
+ <Viz
814
+ {...plot(rows, {x: "plate"})
815
+ .bar({aes: {y: "yield"}, aggregate: "mean"})
816
+ .line({aes: {y: "kd"}, aggregate: "mean", axis: "y2"})
817
+ .labs({headline: "Yield holds while affinity drifts", y: "Yield", y2: "KD"})
818
+ .props()}
819
+ />
820
+ ```
821
+
822
+ The color and fill scales take `limits`, `center`, `transform`, `format`, `decimals`, `bins`, `breaks`, `labels`,
823
+ `standardize` and `values`. `bins` are cuts that step the map, and `breaks` and `labels` name the values the legend
824
+ writes, the shapes a position scale uses. A layer's own `scales.color` or `scales.fill` wins over the chart's field by
825
+ field.
826
+
827
+ `values` names a color per category, ggplot's `scale_fill_manual(values = …)`. It is the host's own vocabulary, such
828
+ as an amino acid colored by its chemistry, and it stays outside the palette switcher. Bars, points, lines and heatmap
829
+ cells take their mapped category's color. A category it leaves out draws in one ink, and the footer counts it.
830
+ `legend(options)` takes the `position`, `align`, `direction`, `fontSize` and `order` of the legends, outside the plot
831
+ area per rule 2. `position` is `right`, `left`, `top`, `bottom` or `none`, `align` is `start`, `center` or `end`,
832
+ `direction` is `horizontal` or `vertical`, and `order` is `geoms` or `authoring`.
833
+
834
+ ## Facets
835
+
836
+ ```ts
837
+ plot(penguins, {x: "body_mass", y: "bill_len"}).point().facet("species", {columns: 3});
838
+ ```
839
+
840
+ `facet(by, {columns})` writes `facet: {by, columns}`, ggplot's `facet_wrap(~by, ncol =)`: one panel per value, up to
841
+ twelve, and the footer counts the rest. Absent, `columns` divides the width by the narrowest panel worth a column. The
842
+ panels share their scales, and the frame builds them once across the grid. A stated `height` is the whole grid's, and
843
+ its rows divide it.
844
+
845
+ ## Sizing: three ways to set it
846
+
847
+ A panel measures the element it is inside, which keeps a figure readable as the page reflows. Override it for a fixed
848
+ size:
849
+
850
+ ```tsx
851
+ .canvas({width: 468, height: 240}) // this figure is this size
852
+ .canvas({height: 240}) // 240 tall, width from the layout
853
+ .canvas({aspect: 9 / 16}) // a wide strip, at any container width
854
+ .canvas({aspect: 1}) // square, which is the shape a cube wants
855
+
856
+ <div style={{maxWidth: 420}}>
857
+ <Viz {...chart.props()} /> // narrower, because the container is
858
+ </div>
859
+ ```
860
+
861
+ | Set | Width | Height |
862
+ | -------------------- | -------- | -------------- |
863
+ | neither | measured | 320 |
864
+ | `height` | measured | as given |
865
+ | `aspect` | measured | width × aspect |
866
+ | `width` | as given | 320 |
867
+ | `width` and `height` | as given | as given |
868
+ | `width` and `aspect` | as given | width × aspect |
869
+
870
+ `aspect` is panel height over panel width, ggplot's `aspect.ratio`: 2 draws a panel twice as tall as it is wide.
871
+ `width` sizes the element as well as the drawing. A figure with a size of its own reserves the room it draws in. An
872
+ aspect resolves against the width one panel got, and a facet's twelve panels each keep the shape. An explicit `height`
873
+ is the more specific instruction and wins over `aspect`. All of them travel on the spec, and a saved figure keeps its
874
+ size.
875
+
876
+ `sizing: "container"`, the default, fills the room the figure is given. `sizing: "content"` lets a stated `bandSize`
877
+ decide the plot area. The cube kinds compute their projection from the same pair, and a panel wider than it is tall
878
+ frames the cube.
879
+
880
+ ## Side panels: four things beside the geoms
881
+
882
+ A dendrogram, an annotation track, a marginal histogram and a rug are one primitive. Each is a panel sharing one axis
883
+ with the plot and taking a fixed extent on the other. The position picks the shared axis: top and bottom share x, left
884
+ and right share y.
885
+
886
+ ```tsx
887
+ <Viz
888
+ {...plot(rows, {x: "assay", y: "lot", z: "response"})
889
+ .heatmap({aggregate: "mean"})
890
+ .labs({headline: "Four response profiles, found again"})
891
+ .scales({y: {bandSize: 12, order: {kind: "cluster", distance: "correlation", cut: 4}}})
892
+ .side(
893
+ {position: "left", size: 14, content: {kind: "track", field: "site"}},
894
+ {position: "left", size: 50, content: {kind: "dendrogram"}},
895
+ )
896
+ .canvas({sizing: "content"})
897
+ .props()}
898
+ />
899
+ ```
900
+
901
+ | Content | Geoms drawn | Requirements |
902
+ | ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------ |
903
+ | `{kind: "dendrogram", depth?}` | The merge order and heights the cluster order came out of | `scales.<x\|y>.order` with `kind: "cluster"` |
904
+ | `{kind: "track", field, palette?, dropLevels?}` | One cell per category, off another column | A band axis, and a column with a reading per category |
905
+ | `{kind: "track"}` on a band of measures | One cell per measure, off that measure's own declaration | A grid that spread `dimensions`, and a `PlotField` property |
906
+ | `{kind: "histogram", binwidth?}` | The readings along the shared axis, binned | A value axis and point geoms |
907
+ | `{kind: "density", by?}` | The readings along the shared axis as a kernel density | The same. `by: "color"` draws a curve per level of the color |
908
+ | `{kind: "rug"}` | One tick per reading | The same |
909
+
910
+ `size` is the extent perpendicular to the shared axis, in pixels: pheatmap's `treeheight_row` for a tree, one cell's
911
+ worth for a track, whatever a marginal is worth. A position takes as many panels as you declare and they stack
912
+ outward, first declared nearest the geoms, matching the order pheatmap draws a dendrogram above an annotation track
913
+ in.
914
+
915
+ What a panel draws picks the side of the axis labels it takes, and `inside` overrides that. A track goes between the
916
+ labels and the geoms, which lets a reader trace a row straight across into the cells. A tree goes outside, because it
917
+ explains the order across all the rows. The order across a left edge comes out as tree, row names, track, geoms.
918
+
919
+ `depth` says how a merge's height becomes the depth it draws at. `height` is the distance itself, matching R's own
920
+ plot. `sqrt` and `rank` open out a tree whose clusters are tight and far apart. Correlation distance over four blocks
921
+ of lots puts sixty of sixty-three merges into the first eighth of the panel under `height`. `sqrt` gives them a third
922
+ of it and leaves the deep structure room. `rank` spaces the merges evenly and flattens the split a cut is read off.
923
+
924
+ `dropLevels` is on by default, and a track legend names the values this figure drew. Turn it off to name each value
925
+ the figure set pinned on the field, which gives two figures of one set the same legend.
926
+
927
+ A grid that spread `dimensions` is the one case where a band has measures. A track there binds a property of the
928
+ field: `field: "unit"` colors each column by the unit it is read in, and `field: "target"` maps them by the cut each
929
+ was gated on. Text reads as identity and a number as a magnitude, the same two shapes a column track produces.
930
+
931
+ A track on a category takes the categorical map and joins the categorical legend. A track on a measure takes the mean
932
+ over each group and a sequential map named by `palette`, kept apart from the cells' so the two magnitudes stay
933
+ distinct, and draws its own color bar. Both legends are labeled with their column. Two magnitude maps on a figure is
934
+ the ceiling, and a third draws `magnitudes-past-legible`.
935
+
936
+ Sides are part of the spec, and a saved figure keeps its dendrogram when it leaves the app that drew it. A figure with
937
+ `sizing: "content"` asks for the panels' room on top of its band size, which keeps the rows at the height they were
938
+ given. A cluster order belongs to the panel that computed it, and sides apply to a figure that draws one panel.
939
+
940
+ ## Naming things: numbers, direct labels and categories
941
+
942
+ ```tsx
943
+ <Viz
944
+ {...plot(rows, {x: "assay", y: "lot", z: "response"})
945
+ .heatmap({aggregate: "mean", numbers: {format: "fixed", decimals: 2, fontSize: 7}})
946
+ .labs({headline: "…"})
947
+ .scales({y: {labels: {L4: "Reference lot"}}})
948
+ .scale("fill", {
949
+ standardize: "row",
950
+ breaks: [-1, 0, 1],
951
+ labels: {"-1": "-1 SD", "0": "mean", "1": "+1 SD"},
952
+ })
953
+ .props()}
954
+ />
955
+ ```
956
+
957
+ `numbers` writes each cell's own value inside it, which is pheatmap's `display_numbers`. `directLabels` names a
958
+ field on the geom, and `numbers` writes the reduction the geom already computed. `format` and
959
+ `decimals` fall back to the layer's color or fill scale, which lets a figure state its measure's shape once. The ink is
960
+ picked per cell off the fill's own luminance, and `color` overrides that. A cell tighter than its number draws
961
+ `numbers-below-legible`, checked in both directions and against the band the layout picked.
962
+
963
+ `numbers.when` writes the cells past a cut. The comparison runs against the value in the units the map reads, and a grid
964
+ with `standardize: "row"` thresholds in standard deviations. `numbers` also writes on a pie, a sunburst, a gauge, a
965
+ chord and an ideogram.
966
+
967
+ `directLabels` names the notable few, per rule 2. `{field, when}` picks the field and the geoms: `{kind: "all"}`,
968
+ `{kind: "top", count, on, end}` for the highest or lowest along an axis, or `{kind: "threshold", on, op, value}` for
969
+ whatever crosses a spec limit.
970
+
971
+ `scales.<x|y>.labels` writes a category as something other than its own value, which is pheatmap's `labels_row` and
972
+ `labels_col`. Key it by value. A name then stays with its row through a clustering reorder. A category you leave out
973
+ is written as itself, and the margin grows to fit whichever name is longest.
974
+
975
+ A color or fill scale's `breaks` names the values the legend writes under its bar, and `labels` writes each one,
976
+ `legend_breaks` and `legend_labels` in pheatmap's terms. Each label lands at its own value's position along the bar,
977
+ which puts a named threshold where the color changes. A break with no label writes the value through the scale's own
978
+ format.
979
+
980
+ ## `Viz`: drawing from a spec
981
+
982
+ `Viz` is the one component the package draws through. Hand it a `ChartSpec` and the rows, and it draws. The builder
983
+ writes one, a store hands one back, the panel edits one, and all of them take this route.
984
+
985
+ ```tsx
986
+ import {Viz} from "@tetrascience-npm/ts-lib-viz/react";
987
+
988
+ <Viz spec={saved} data={rows} />;
989
+ ```
990
+
991
+ | Prop | Type | Effect |
992
+ | ---------------- | -------------------------------------- | ------------------------------------------------------------------------ |
993
+ | `spec` | `ChartSpec` | **Required.** What is drawn. The chart itself |
994
+ | `data` | `VizData` | **Required.** Rows, columns, an Arrow table or a `PlotData` |
995
+ | `fieldOverrides` | `Record<string, FieldOverride>` | Units, labels, log defaults and targets the table lacks, keyed by column |
996
+ | `keyField` | `string` | The column naming each record. Defaults to the first text column |
997
+ | `set` | `FigureSet` | Color pinning across the figures of one page |
998
+ | `palettes` | `Palettes` | The color maps. The package's own, on the theme's paper, where absent |
999
+ | `fitter` | `Fitter` | What answers a `LayerSpec.fit` or a smooth. Absent draws the geoms alone |
1000
+ | `zoom` | `boolean` | Whether a wheel and a drag move the view. Opt in |
1001
+ | `brush` | `"box" \| "lasso"` | What a drag across a scatter selects. Opt in |
1002
+ | `onBrush` | `(brushed: Brushed \| null) => void` | The rows, keys and filter inside the region |
1003
+ | `toolbar` | `ToolbarOptions` | A ghost strip of reader controls over the figure. Absent draws none |
1004
+ | `onCritique` | `(findings: Finding[]) => void` | Fires when the findings change |
1005
+ | `onSelect` | `(selected: Selected \| null) => void` | The geom clicked, with the rows, keys and filter behind it |
1006
+
1007
+ The chart is the spec, and `plot()` is where you state it. An aesthetic maps a field id, which is the vocabulary the
1008
+ profile gates, the critic reports paths in, and the builder binds. `fieldOverrides` and `set` compare by content, and
1009
+ an inline object stays stable across renders. `palettes` compares by identity, because a map is a function, and a
1010
+ new object each render rebuilds the figure.
1011
+
1012
+ ## `plot()`: the builder
1013
+
1014
+ `Viz` takes a document and the chain emits one, which keeps the schema to what a store round trips.
1015
+
1016
+ ```tsx
1017
+ import {plot} from "@tetrascience-npm/ts-lib-viz/core";
1018
+
1019
+ <Viz
1020
+ {...plot(penguins, {x: "body_mass", y: "bill_len"})
1021
+ .point()
1022
+ .smooth({method: "loess", span: 0.75})
1023
+ .smooth({method: "lm", band: false, color: "#b23"})
1024
+ .facet("species")
1025
+ .labs({headline: "Bill length tracks mass within species"})
1026
+ .props()}
1027
+ fieldOverrides={FIELDS}
1028
+ fitter={fitter}
1029
+ />;
1030
+ ```
1031
+
1032
+ The chain adds three things R has:
1033
+
1034
+ | What | R | Here |
1035
+ | -------------------------- | --------------------- | -------------------------------------------------------- |
1036
+ | The aes reaches each layer | `aes()` on `ggplot()` | the second argument to `plot()` |
1037
+ | Arguments have defaults | the argument list | `level` 0.95 and `band` on. Each geom's own at draw time |
1038
+ | A layer appends | `+` | a method per kind, or `layer(kind, options)` |
1039
+
1040
+ A layer states the aesthetics that differ from the plot's aes and inherits the rest its kind reads, and its `aes` option
1041
+ merges. An aesthetic the layer's own `aes` states that its kind reads nowhere throws:
1042
+
1043
+ ```tsx
1044
+ plot(rows, {x: "kd", y: "tm", color: "lot"})
1045
+ .point() // x, y and color
1046
+ .line({aes: {y: "yield"}, axis: "y2"}) // x and color inherited, y its own
1047
+ .labs({headline: "Yield holds while affinity drifts"});
1048
+ ```
1049
+
1050
+ ### The layer methods
1051
+
1052
+ One method per kind, named for it: `point()`, `line()`, `area()`, `ribbon()`, `errorbar()`, `linerange()`,
1053
+ `pointrange()`, `crossbar()`, `segment()`, `smooth()`, `bar()`, `waterfall()`, `histogram()`, `freqpoly()`, `hex()`,
1054
+ `boxplot()`, `violin()`, `density()`, `heatmap()`, `contour()`, `parcoords()`, `sankey()`, `chord()`, `ideogram()`,
1055
+ `treemap()`, `icicle()`, `sunburst()`, `pie()`, `gauge()`, `radar()`, `point3d()`, `surface()`, `mesh3d()`,
1056
+ `isosurface()`, `volume()`, `hline()`, `vline()`, `abline()`, `text()` and `label()`. `fit()` writes a `point` layer
1057
+ with a model.
1058
+
1059
+ The geom table narrows each method's argument list to the paints, the style fields and the parts its geometry reads,
1060
+ the layer fields its statistic reaches, the statistic's parameters, and the aesthetics the plot's aes left open:
1061
+
1062
+ ```tsx
1063
+ plot(rows, {x: "day"}).ribbon({aes: {ymin: "lo", ymax: "hi"}}); // x from the plot's aes, two bound here
1064
+ plot(rows, {x: "kd", y: "tm"}).point(); // the plot's aes binds all a point requires
1065
+ ```
1066
+
1067
+ An aesthetic the plot's aes bound drops to optional, and a layer overrides it or inherits it. A layer takes rows of
1068
+ its own through `data`, which is ggplot's `data` argument, and places its own `x` against the shared axis.
1069
+ `showLegend: false` keeps it out of each guide:
1070
+
1071
+ ```ts
1072
+ plot(compounds, {x: "observed", y: "predicted"})
1073
+ .point()
1074
+ .line({data: folds, aes: {x: "ref_x", y: "ref_y", group: "line"}, showLegend: false});
1075
+ ```
1076
+
1077
+ `visible: false` keeps a layer on the spec and leaves it out of the drawing and the critic's checks. The property
1078
+ column's show and hide toggle writes it.
1079
+
1080
+ The rows save with the spec. A column sharing an id with the chart's table takes that field's label and unit, and a
1081
+ category in both tables takes one color. Under a facet, rows with the facet column fall to their own panel and the
1082
+ rest repeat in each.
1083
+
1084
+ `smooth()` and `fit()` ask different questions of the same solver. See [Fits](#fits-the-service-boundary).
1085
+
1086
+ ### The chart methods
1087
+
1088
+ | Method | Field |
1089
+ | --------------------------- | --------------------------------------------------------------- |
1090
+ | `labs(words)` | `headline`, `subtitle`, `caption`, `scales[aesthetic].title` |
1091
+ | `facet(by, {columns?})` | `facet` |
1092
+ | `flip()` | `coord`, as `"flip"` |
1093
+ | `fixed(ratio?)` | `ratio`, one by default |
1094
+ | `scale(aesthetic, options)` | `scales[aesthetic]`, merged |
1095
+ | `scales(options)` | `scales`, merged per aesthetic |
1096
+ | `log(aesthetic?)` | `scales[aesthetic].transform` as `"log10"`, `y` by default |
1097
+ | `legend(options)` | `legend` |
1098
+ | `tooltip(fields)` | `tooltip`, the columns the hover card adds after the bound ones |
1099
+ | `side(...panels)` | `sides`, appending |
1100
+ | `annotate(...notes)` | `annotations`, appending |
1101
+ | `annotate(kind, values)` | a one-off layer, ggplot's `annotate()` |
1102
+ | `canvas(options)` | `width`, `height`, `aspect`, `sizing` |
1103
+ | `override(...codes)` | `overrides`, appending |
1104
+
1105
+ ### A persistent chain
1106
+
1107
+ Each method returns a new builder and leaves the one it was called on as it was. A base plot branches into as many
1108
+ charts as you build from it, and `spec()` hands out objects of its own:
1109
+
1110
+ ```ts
1111
+ const base = plot(rows, {x: "kd", y: "tm"}).labs({headline: "Two clusters"});
1112
+ const dots = base.point();
1113
+ const shaded = base.hex(); // base still holds no layer
1114
+ ```
1115
+
1116
+ `PlotBuilder` is exported as a type, and `plot()` is the one constructor. The methods are on the prototype and read
1117
+ `this`, and a method taken off a builder and called on its own loses it. A spec states what the author wrote and nothing more: no default
1118
+ style, axis or visibility lands on a layer, and each geom takes its own default at draw time. A layer's id is its kind
1119
+ and its position, `point0`, and two builds from one piece of code compare equal.
1120
+
1121
+ ### `spec()` and `props()`
1122
+
1123
+ `spec()` returns the `ChartSpec`, the thing a store saves, stamped with `version: SPEC_VERSION`. `props()` returns it
1124
+ with the rows beside it, the pair `Viz` takes.
1125
+
1126
+ A figure builds and draws as soon as it has geoms. `blocking` is the gate, and it refuses a figure with no headline
1127
+ whatever the overrides say. Publishing requires a claim and exploring leaves it open:
1128
+
1129
+ ```tsx
1130
+ const spec = plot(rows, {x: "kd", y: "tm"}).point().spec(); // draws
1131
+ blocking(spec, critique(spec)); // [{severity: "wrong", code: "headline-missing", …}]
1132
+ ```
1133
+
1134
+ A headline of whitespace reads the way an empty one does, and the field is dropped. `override("headline-missing")`
1135
+ fails to compile: the code is an `UnwaivableCode`.
1136
+
1137
+ ## Selection: `onSelect` and `keyField`
1138
+
1139
+ ```tsx
1140
+ <Viz spec={saved} data={rows} keyField="lot" onSelect={(selected) => setPicked(selected?.keys ?? [])} />
1141
+ ```
1142
+
1143
+ A click on a geom hands `onSelect` a `Selected`, and a click on empty ground hands it `null` once a selection exists.
1144
+
1145
+ | Field | Contents |
1146
+ | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
1147
+ | `layerId` | The layer the geom belongs to |
1148
+ | `kind` | The kind of that layer, a `PlotKind`: a pie's slice reads `pie` and a box reads `boxplot` |
1149
+ | `datum` | The record the geom stands for, field by field, as the layer's table reads it. Null where it stands for several or none |
1150
+ | `rows` | Rows of the table the layer read, ascending, each once. A point or a segment names its own row |
1151
+ | `keys` | The same records' keys, where the key column names each record once. Empty otherwise |
1152
+ | `predicate` | A `Predicate` for the same records, or null where the geom stands for nothing a query names |
1153
+
1154
+ `keyField` names the column a click, a brush and the tooltip title name records by, and the first text column is the
1155
+ default. A click or a brush emits a key filter only where each key names one row. A key naming two rows names a group:
1156
+ a click then filters by the values the geom stands for, and a lasso has no filter.
1157
+
1158
+ `Predicate` is a filter as data, which runs in a SQL compiler, a pass over columnar batches or a toolbar chip.
1159
+ `leaves` lists the leaf predicates in force.
1160
+
1161
+ | `kind` | Fields |
1162
+ | ----------- | ------------------------------------------------------ |
1163
+ | `text` | `fields`, `needle` |
1164
+ | `range` | `field`, `lo`, `hi`, either one null for an open end |
1165
+ | `in` | `field`, `values` |
1166
+ | `eq` | `field`, `value`, `negate` |
1167
+ | `regex` | `field`, `pattern`, `caseInsensitive` |
1168
+ | `null` | `field`, `negate` |
1169
+ | `time` | `field`, `from`, `to`, either one null for an open end |
1170
+ | `and`, `or` | `of`, a list of predicates |
1171
+ | `not` | `of`, one predicate |
1172
+
1173
+ ## Zoom: the reader's own window
1174
+
1175
+ ```tsx
1176
+ <Viz spec={saved} data={rows} zoom />
1177
+ ```
1178
+
1179
+ A wheel closes in on the value under the cursor, a drag moves the window, and a double-click returns to rest. The
1180
+ gesture rewrites the domain the axes state. The ticks say what is on screen and the geoms keep the size they were
1181
+ drawn at.
1182
+
1183
+ The traces stay as they are. The rows and the bindings decide what a trace contains, and the pass that walked
1184
+ nineteen thousand records runs once. While the view is off rest, the footer line picks up `showing part of the range`.
1185
+
1186
+ Zoom is opt-in through the prop, which leaves a chart in a page of prose scrolling with the page. A faceted chart
1187
+ draws at rest, because a small multiple compares panels over shared scales. `scales.x.limits` is the author's fixed
1188
+ window and works alongside this. Zoom belongs to the reader, which is why it is outside the spec.
1189
+
1190
+ ## Brush: a box or a lasso over a scatter
1191
+
1192
+ ```tsx
1193
+ <Viz spec={ivive} data={compounds} brush="lasso" onBrush={(brushed) => setPicked(brushed?.keys ?? [])} />
1194
+ ```
1195
+
1196
+ `brush` makes a drag across a scatter's plot area select a region: `"box"` between two corners, and `"lasso"` along
1197
+ the path the hand draws. These are plotly's box and lasso select, and Shiny's `brushedPoints` over a ggplot. The drag
1198
+ selects in place of panning, and a wheel still zooms. A click with no drag clears the region. A faceted figure takes
1199
+ no brush, as it takes no zoom.
1200
+
1201
+ `onBrush` receives a `Brushed`:
1202
+
1203
+ | Field | Contents |
1204
+ | ----------- | ---------------------------------------------------------------------------------- |
1205
+ | `shape` | `box` or `lasso`, the `BrushShape` dragged |
1206
+ | `region` | The box's corners or the lasso's vertices, in data units |
1207
+ | `rows` | The table rows inside the region, tested at the pixel each geom draws at |
1208
+ | `keys` | The same records' keys, where a key column names each record once, empty otherwise |
1209
+ | `predicate` | Ranges for a box over two value axes, `in` over the keys for the rest, or null |
1210
+
1211
+ A row indexes the table the layer read. `rowIndex(row)` on that table names the row's place in the source.
1212
+
1213
+ `rows`, `keys` and `predicate` have the names and types they have on `Selected`, and a host narrows the tables beside
1214
+ the figure the same way for both gestures. A log axis states its ranges in the data's own units. A layer with rows of
1215
+ its own, a reference or a label, is left out. The region stays drawn in data units, and a zoom redraws it over the same
1216
+ records.
1217
+
1218
+ ## Toolbar: the reader's controls
1219
+
1220
+ ```tsx
1221
+ <Viz
1222
+ spec={saved}
1223
+ data={rows}
1224
+ toolbar={{
1225
+ items: ["zoom", "reset", "pan", "zoomBox", "box", "lasso", "tooltip", "palette", "colorblind", "facet", "export"],
1226
+ palette: {options: ["okabe-ito", "viridis", "tetra-rainbow"]},
1227
+ facet: {by: ["plate", "lot"], columns: [1, 2, 3, 4]},
1228
+ export: {formats: ["png", "svg"]},
1229
+ }}
1230
+ />
1231
+ ```
1232
+
1233
+ `toolbar` draws a strip of icons in the plot area's top-right corner, plotly's modebar. It fades in while the pointer is
1234
+ over the figure or focus is inside it, and stays up while one of its menus is open. A touch screen shows it at rest,
1235
+ half lit. `items` is a list of `ToolbarItem` names, drawn in the order listed, and the strip offers those alone.
1236
+ A tool under the pointer or holding focus shows its name at once in a dark tip under it, drawn as the UI kit's
1237
+ tooltip from the `--viz-tooltip-*` tokens. A locked tool's tip gives the reason.
1238
+
1239
+ | Item | Effect |
1240
+ | -------------------------------- | ------------------------------------------------------------------------------------- |
1241
+ | `zoom` | A step in and a step out about the plot area's center |
1242
+ | `reset` | Returns the view to rest, as a double-click does |
1243
+ | `pan`, `zoomBox`, `box`, `lasso` | What a drag does: move the window, zoom to a box, or select as `brush` does |
1244
+ | `tooltip` | Turns the hover card on and off |
1245
+ | `palette` | A menu of the listed maps that suit the figure's color kind |
1246
+ | `colorblind` | Moves each map to the colorblind-safe one of its kind: `okabe-ito`, `cividis`, `puor` |
1247
+ | `facet` | A menu of the fields to facet by and the column count |
1248
+ | `export` | Saves the figure as `exportPng` or `exportSvg` draws it, named off the headline |
1249
+
1250
+ A choice belongs to the reader, as a zoom does. The spec stays as authored, a reload returns to it, and
1251
+ `toolbar.onChange` reports the choices as a `ToolbarView`: `drag`, the drag mode in force, `tooltip`, `palette`,
1252
+ `colorblind`, and `facet`, a `{by, columns}` where a null `by` draws one panel. A field the reader left alone is absent.
1253
+ The first listed drag mode is in force at first, or `brush` where the list names it. The wheel stays with the `zoom`
1254
+ prop. Under a facet the view tools are off, and on a figure with side panels the facet menu is off. `palette.options`
1255
+ absent offers the registry's maps of the figure's color kind, `facet.by` absent offers the text fields, and `colorblind`
1256
+ takes a target per kind over the three above. `export.ground: false` saves an SVG with no paper behind it.
1257
+
1258
+ ## Out of bounds: readings a scale drops
1259
+
1260
+ ```ts
1261
+ plot(rows, {x: "observed", y: "predicted"})
1262
+ .point()
1263
+ .scales({x: {transform: "log10", limits: [3, 300]}, y: {transform: "log10", limits: [3, 300]}});
1264
+ ```
1265
+
1266
+ A log axis reads its span off the positive readings. On a log axis, a position at or below zero leaves the figure,
1267
+ and the footer counts it. An interval or a whisker whose low bound reaches zero runs to the axis floor, where ggplot
1268
+ draws `-Inf`, and the footer counts that too.
1269
+
1270
+ `oob` on a position scale decides what a reading past stated `limits` becomes. The three values are ggplot's:
1271
+
1272
+ | `oob` | A point past the limits |
1273
+ | --------------------- | ---------------------------------------------- |
1274
+ | `censor`, the default | Leaves the figure, and the footer counts it |
1275
+ | `squish` | Draws at the edge of the range |
1276
+ | `keep` | Draws where it falls, clipped at the plot area |
1277
+
1278
+ Censoring reads positions. The length of a bar and the bounds of an interval are extents, and the plot area clips
1279
+ them. ggplot censors a bar too, which empties a bar chart whose limits leave out zero. Rule 11 grounds a bar at zero,
1280
+ and the frame clips it. The plot area clips whenever an axis states limits, and under a zoom.
1281
+
1282
+ A reference line past the axis domain draws nothing, and the footer counts it. ggplot's reference geoms leave the
1283
+ scales alone, and a line past the data needs `limits` that reach it.
1284
+
1285
+ ## Reference lines: `hline`, `vline` and `abline`
1286
+
1287
+ ```ts
1288
+ const fold = Math.log10(2);
1289
+ plot(compounds, {x: "observed", y: "predicted"})
1290
+ .point()
1291
+ .abline({label: "1:1"})
1292
+ .abline({intercept: [fold, -fold], label: "2-fold", linetype: "dotted"})
1293
+ .scales({x: {transform: "log10", limits: [3, 300]}, y: {transform: "log10", limits: [3, 300]}});
1294
+ ```
1295
+
1296
+ The three are ggplot's `geom_hline`, `geom_vline` and `geom_abline`, drawn as layers. A number or a list of them becomes
1297
+ the layer's own rows, as ggplot's arguments make a data frame, and each row draws a line. With a column bound through
1298
+ the aes, the positions come off the rows, and a layer with its own `data` reads those:
1299
+
1300
+ ```ts
1301
+ .hline({data: potencies, aes: {yintercept: "value", label: "name", color: "compound"}})
1302
+ ```
1303
+
1304
+ `abline` reads its slope and intercept in the scales' transformed space, as ggplot does. On two log axes a 2-fold line
1305
+ is an intercept of `log10(2)` at slope one, and with neither argument the layer draws the identity line. A reference
1306
+ layer inherits no aes and trains no scale. It takes `color`, `linewidth`, `linetype` and `alpha` constants, draws rule
1307
+ 4's dotted foreground unless it maps or states a color, writes each `label` where its line ends, and reaches the
1308
+ legend only where it maps color or linetype. A layer naming nothing it marks is reported as `unlabeled-reference`. A
1309
+ reference layer with no position throws.
1310
+
1311
+ ## Text and annotations
1312
+
1313
+ ```ts
1314
+ plot(exposure, {x: "dose", y: "auc"})
1315
+ .bar({aes: {fill: "regimen"}, position: "dodge"})
1316
+ .text({aes: {label: "multiple", group: "regimen"}, position: "dodge", vjust: -0.5})
1317
+ .annotate("text", {x: "30", y: 26000, label: "first past 10x"})
1318
+ .annotate("hline", {yintercept: 10000, label: "10x"});
1319
+ ```
1320
+
1321
+ `text` and `label` are ggplot's `geom_text` and `geom_label`: a label per row at its reading, the second with a paper
1322
+ box behind it. `hjust` and `vjust` read ggplot's way, zero to one across and up the anchor, and `vjust: -0.5` lifts a
1323
+ label clear of a bar's top. Under a dodge a text layer takes the slot of the bar it names, matched by the split value.
1324
+ The labels train the axes, censor past stated limits, and keep out of the legend unless the layer asks for one.
1325
+
1326
+ `annotate(kind, values)` is ggplot's `annotate()`: a one-off layer off constants, with no aes inherited and no legend
1327
+ row. The kind's required aesthetics take a value or a list, and a list writes a row each. Each other key is a
1328
+ constant. A reference kind takes numbers for its positions.
1329
+
1330
+ `annotate(...notes)` appends to `annotations`, what the author wrote on the chart. A `note` writes text at a data
1331
+ `Anchor`, an `{x, y}` in the axes' own values, and `align` sets the text `left`, `center` or `right`. Its optional
1332
+ `Leader` draws a `straight` or `curved` line `toward` a second anchor. An `axis-end` writes a caption at the `low` or
1333
+ `high` end of the `x` or `y` axis. Those two are the `Annotation` union. The builder panel offers the axis-end captions
1334
+ a measure's `direction` seeds.
1335
+
1336
+ ## Fits: the service boundary
1337
+
1338
+ A layer asks for a curve through it, and your `Fitter` computes it:
1339
+
1340
+ ```tsx
1341
+ plot(wells, {x: "dose", y: "response"}).fit({model: "4pl"}).log("x").labs({headline: "EC50 holds across lots"});
1342
+ ```
1343
+
1344
+ `level` and `band` default to 0.95 and on. A request states the model.
1345
+
1346
+ ### `PredictionBand` to `Fit`
1347
+
1348
+ `ts-lib-stats.predict_band` answers with a `PredictionBand`: four aligned arrays plus the level, the scale and the
1349
+ reference degrees of freedom. Three of those map straight across.
1350
+
1351
+ | `PredictionBand` | `Fit` |
1352
+ | ---------------- | -------------------- |
1353
+ | `x` | `curveX` |
1354
+ | `fit` | `curveY` |
1355
+ | `lower`, `upper` | `band.lo`, `band.hi` |
1356
+
1357
+ The rest of `Fit` was cut for a parametric model, and a smoother fills it differently. A smoother reports an empty
1358
+ `params` with `r2` and `rmse` as null, because a local regression's goodness belongs outside a chart. `n` is the count
1359
+ of points behind the curve. A 4PL fills all four.
1360
+
1361
+ `panel` comes back verbatim. It lets a faceted plot hand each panel the curve fitted on its own rows.
1362
+
1363
+ `demo/src/fitter.ts` is this written out. `fitFrom` is the mapping, `serviceFitter` calls a service one layer at a
1364
+ time, `recordedFitter` answers from coordinates already in hand, which is the shape a test takes, and
1365
+ `precomputedFitter` answers from fits made ahead of the chart.
1366
+
1367
+ The answer comes from your service, because a reader takes an EC50 off the chart and orders material against it. The
1368
+ curve has to match the platform report. `ts-lib-stats` parameterizes 4PL as `(bottom, top, ec50, hill)` and builds its
1369
+ interval by the delta method. The package ships the contract and calls out to that.
1370
+
1371
+ ```tsx
1372
+ import type {Fitter} from "@tetrascience-npm/ts-lib-viz/core";
1373
+
1374
+ const fitter: Fitter = async (requests) => {
1375
+ const answer = await post("/stats/fit", requests);
1376
+ return new Map(answer.map((entry) => [entry.layerId, {fits: entry.fits, dropped: entry.dropped}]));
1377
+ };
1378
+
1379
+ <Viz spec={saved} data={rows} fitter={fitter} />;
1380
+ ```
1381
+
1382
+ A `FitRequest` sends the `layerId`, the author's `FitSpec` or `SmoothSpec` as `spec`, and the points under it as
1383
+ `groups`, one `FitGroup` of `{id, panel, points}` per value of the layer's `group` or categorical `color`. The groups come off
1384
+ the traces the frame built, and the solver sees the groups that survived the split cap. `Fit.curveX` and `Fit.curveY`
1385
+ are the positions the service chose, and the geom draws them as given, which keeps the reader looking at the model. The
1386
+ answer is a `LayerFits` per layer id, with `dropped` counting the groups a cap refused.
1387
+
1388
+ The chart draws while the answer is in flight, because the geoms are correct on their own. The footer line says
1389
+ `fitting` meanwhile, and a refusal puts the reason there. Bands draw up to twelve curves, and the footer line records
1390
+ the rest. `fitSignature` is what `Viz` refits on: the model, the interval, the grouping and a hash of the coordinates.
1391
+ A hover or a recolor leaves the solver alone.
1392
+
1393
+ A **faceted** plot fits per panel. The fitter receives one request per layer whatever the panel count, and each group
1394
+ inside it names the `panel` it came from. A `Fit` echoes that value back, which is how a panel picks up the curve
1395
+ fitted on its own rows. The panel is a field of its own, kept apart from the group's `id`, which lets a lot name use
1396
+ any character and still round trip.
1397
+
1398
+ ### Smooth and fit: two spec shapes
1399
+
1400
+ A curve answers one of two questions and the spec keeps the two apart.
1401
+
1402
+ **A smooth is a layer.** The curve is the deliverable, it draws a curve on its own, and the five methods are the ones
1403
+ `geom_smooth()` offers:
1404
+
1405
+ ```tsx
1406
+ plot(rows, {x: "body_mass", y: "bill_len"}).point().smooth({method: "lm"}).labs({headline: "Bill length tracks mass"});
1407
+ ```
1408
+
1409
+ | Method | Its own arguments | State |
1410
+ | ------- | -------------------------------------------- | --------------------------- |
1411
+ | `loess` | `span`, the window each local fit reads | needs the library |
1412
+ | `lm` | `degree`, above one bends it | modeled, needs a curve seam |
1413
+ | `glm` | `family`: gaussian, binomial, poisson, gamma | modeled, needs a curve seam |
1414
+ | `rlm` | none | needs the library |
1415
+ | `gam` | none | needs the library |
1416
+
1417
+ `ts-lib-stats` implements the model behind `lm` and `glm`, and it emits a curve with a band for the dose-response
1418
+ family, which makes `predict_band` what `loess` waits on. Local regression, additive models and M-estimators are on
1419
+ the library's roadmap. The seam and the drawing live here.
1420
+
1421
+ **A fit is a property.** The parameters are the deliverable and the curve makes them credible. It hangs off the geom
1422
+ that draws the readings underneath it and takes their color and their groups. A reader taking an EC50 off the chart is
1423
+ looking at the wells it came from.
1424
+
1425
+ ```tsx
1426
+ plot(wells, {x: "dose", y: "response", color: "plate"}).fit({model: "4pl"}).log("x").labs({headline: "…"});
1427
+ ```
1428
+
1429
+ One `Fitter` answers both. A `Fit` answers a group by its `id` and `panel` and returns `success`, the coordinates, a band,
1430
+ `params`, `r2`, `rmse`, `n` and a `reason`, and the figure draws whichever arrived. A fit with `success: false` draws
1431
+ dashed, with the service's own reason attached.
1432
+
1433
+ See the ADR "A smooth is a layer and a fit is a property of one".
1434
+
1435
+ ## Data: three shapes, one path
1436
+
1437
+ ```ts
1438
+ import {toPlotData, fromRows, fromColumns, fromArrow} from "@tetrascience-npm/ts-lib-viz/core";
1439
+
1440
+ toPlotData(rows); // array of objects
1441
+ toPlotData({kd: Float64Array.from(…), tm: Float64Array.from(…)}); // columns
1442
+ toPlotData(arrowTable, {fieldOverrides: FIELDS, keyField: "lot"}); // anything with numRows and a schema
1443
+ ```
1444
+
1445
+ `toPlotData(data, {fieldOverrides, keyField})` detects the shape. An array is rows. A value with a `schema` and a numeric
1446
+ `numRows` is an Arrow table. A `PlotData` of your own passes through with its own fields, and with its own key unless
1447
+ `keyField` names another, read through its own methods: `fields`, `rowCount`, `number(row, field)`,
1448
+ `text(row, field)` and `rowIndex(row)`, with an optional `keyField` and the whole-column reads `numbers(field)` and
1449
+ `texts(field)`. Anything else is columns, with the row count read off the
1450
+ longest one. `fromRows`, `fromColumns` and `fromArrow` are the three adapters behind it, and each takes the same
1451
+ `AdapterOptions`.
1452
+
1453
+ The Arrow read is structural, through `ArrowLike`: the row count and `toColumns` where the table has it, which is
1454
+ flechette's shape, or `schema.fields` and `getChild`, which is apache-arrow's. A value stating neither accessor fails
1455
+ to compile. A numeric column with no nulls comes through uncopied, and a scatter over a quarter of a million rows
1456
+ projects straight from the arrays the service sent.
1457
+
1458
+ A column whose name says time, with ISO-8601 text, epoch seconds or epoch milliseconds, all of one kind, becomes a
1459
+ numeric timestamp on a calendar scale. A time with no offset reads in UTC. `timeScale: false` or `numeric: false` on
1460
+ the field keeps the column as it arrived.
1461
+
1462
+ `fieldOverrides` is where units arrive, and it retires `bare-numeric-axis` findings at the source:
1463
+
1464
+ ```ts
1465
+ const FIELDS = {
1466
+ kd: {label: "KD", unit: "nM", logScale: true, digits: 2},
1467
+ tm: {label: "Tm", unit: "°C", target: 60},
1468
+ };
1469
+ ```
1470
+
1471
+ A `FieldOverride` takes any `PlotField` property but the id: `label`, `numeric`, `role`, `unit`, `digits`,
1472
+ `logScale`, `timeScale`, `target` and `direction`.
1473
+
1474
+ ## Color
1475
+
1476
+ Ninety-one named maps in one registry, in three kinds kept apart by rule 8 of the design language. A magnitude takes a
1477
+ sequential map, identity takes a categorical one, and a measure read against a neutral takes a diverging one. Nineteen
1478
+ are written by hand:
1479
+
1480
+ | Kind | Names | Default |
1481
+ | ------------- | ------------------------------------------------------------------------------------------------------------ | --------------- |
1482
+ | `categorical` | `tetra-rainbow`, `okabe-ito`, `tetra-brand` | `tetra-rainbow` |
1483
+ | `sequential` | `viridis`, `mako`, `rocket`, `magma`, `inferno`, `plasma`, `cividis`, `giemsa`, `tetra-blue`, `tetra-purple` | `magma` |
1484
+ | `diverging` | `rdbu`, `brbg`, `puor`, `tetra-blue-orange`, `tetra-teal-magenta`, `tetra-purple-yellowgreen` | `rdbu` |
1485
+
1486
+ `DEFAULT_CATEGORICAL`, `DEFAULT_SEQUENTIAL` and `DEFAULT_DIVERGING` name the three defaults. `giemsa` is the stain map
1487
+ an ideogram paints its bands with.
1488
+
1489
+ ```ts
1490
+ import {PALETTES, palettesFor, registerPalette} from "@tetrascience-npm/ts-lib-viz/core";
1491
+
1492
+ registerPalette("house-blues", {label: "House blues", kind: "sequential", stops: ["#08306b", "#6baed6", "#f7fbff"]});
1493
+
1494
+ const palettes = palettesFor({sequential: "house-blues", categorical: "okabe-ito"}); // a Palettes to hand Viz
1495
+ PALETTES.magma.stops; // the shipped anchors, for a legend swatch
1496
+ ```
1497
+
1498
+ `palettesFor(choice)` builds the `Palettes` a figure draws with, from a `PaletteChoice` of map names, a diverging
1499
+ `center` and the `dark` flag. `Palettes` has a `sequential` map over 0..1, a `categorical` map by index with
1500
+ `categoricalSize` distinct colors, and the diverging `center`. Its lookups `sequentialFor` and `categoricalFor` resolve
1501
+ a layer's own `palette`, and `stain` colors an ideogram's bands. `DEFAULT_PALETTES` is what `Viz` draws with where a
1502
+ host hands none on light paper.
1503
+
1504
+ `PALETTES` is the frozen record of the shipped maps. `registerPalette(name, palette)` adds a host's own `Palette` to
1505
+ the registry each reader resolves against: a layer's `palette`, a track's, and a `PaletteChoice`. A shipped name is
1506
+ refused, and registering a name again replaces its map. `PaletteName` lists the shipped names and takes a registered
1507
+ one. The demo's Palettes story ends on three made-up brand maps registered this way.
1508
+
1509
+ `categoricalCss(index, name)` and `sequentialCss(t, name, dark)` sample a map to a CSS color, and `stopsOf(name)` returns
1510
+ a map's stops. A host that shades its own cells or swatches reads the figure's maps through them.
1511
+
1512
+ A layer's `palette` names any map. Over a categorical `color`, a categorical map paints each category with its own
1513
+ stops, and a sequential or diverging map paints them at even steps along itself. A measure sweeps along the named map.
1514
+
1515
+ `tetra-rainbow` is the house set, the same twelve stops the clustering app colors clusters with and the sequence model
1516
+ colors residues with. Identity color agreeing across those surfaces is why it is the default. `okabe-ito` is one name
1517
+ away for a figure that has to stay legible under color-vision deficiency.
1518
+
1519
+ Six maps are the UI kit's chart maps. `tetra-brand` is its `CHART_COLORS`, `tetra-blue` and `tetra-purple` are two of
1520
+ its `CHART_SEQUENTIAL` maps, and `tetra-blue-orange`, `tetra-teal-magenta` and `tetra-purple-yellowgreen` are its
1521
+ `CHART_DIVERGING`. The kit marks each as safe under color-vision deficiency, and the stops match the kit's own. A kit
1522
+ diverging map has twelve stops, and its neutral falls between the sixth and seventh. The kit's teal map stays out of
1523
+ the registry: its eighth stop is lighter than its seventh.
1524
+
1525
+ `tetra-rainbow` also draws a measure. Its entry states `continuous: true`, and a layer naming it sweeps across its stops.
1526
+
1527
+ The other 72 come from R, and `yarn palettes` writes them again from `scripts/palette-sets.R`:
1528
+
1529
+ | Source | Kind | Maps |
1530
+ | -------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1531
+ | `RColorBrewer` | `sequential` | `blues`, `bugn`, `bupu`, `gnbu`, `greens`, `grays`, `oranges`, `orrd`, `pubu`, `pubugn`, `purd`, `purples`, `rdpu`, `reds`, `ylgn`, `ylgnbu`, `ylorbr`, `ylorrd` |
1532
+ | `RColorBrewer` | `diverging` | `piyg`, `prgn`, `rdylbu` |
1533
+ | `RColorBrewer` | `categorical` | `dark2`, `paired`, `set2` |
1534
+ | `hcl.colors` | `sequential` | `light-grays`, `blues-2`, `blues-3`, `purples-2`, `purples-3`, `reds-2`, `reds-3`, `greens-2`, `greens-3`, `oslo`, `purple-blue`, `red-purple`, `red-blue`, `purple-orange`, `purple-yellow`, `blue-yellow`, `green-yellow`, `red-yellow`, `heat`, `heat-2`, `terrain`, `terrain-2`, `dark-mint`, `mint`, `blugrn`, `teal`, `tealgrn`, `emrld`, `bluyl`, `ag-grnyl`, `peach`, `pinkyl`, `burg`, `burgyl`, `redor`, `oryel`, `purp`, `purpor`, `sunset`, `magenta`, `sunsetdark`, `ag-sunset`, `brwnyl`, `lajolla`, `turku`, `hawaii`, `batlow` |
1535
+ | `viridisLite` | `sequential` | `turbo`, the one sequential map whose lightness rises and falls |
1536
+
1537
+ The Brewer rows are the 24 maps `brewer.pal.info` marks safe under color-vision deficiency that the registry did not
1538
+ already ship, with Brewer's gray map as `grays`. The hcl names are lowercase with hyphens, and an hcl map sharing a
1539
+ Brewer or shipped name stays out.
1540
+
1541
+ Each generated sequential map's safe span ends on the last stop clearing 1.5:1 against its paper. The demo's Palettes
1542
+ story draws each map on one board, then a discrete dose-response beside a continuous scatter for each.
1543
+
1544
+ Each sequential map's `safe` states the span of itself that survives each paper, `light` and `dark`. The perceptual maps
1545
+ run from near-black to near-white, and the readable span moves with the paper. `palettesFor({dark})` picks it, and `Viz`
1546
+ passes the flag from the theme it watches where the host hands no `palettes`. A host passing its own states `dark`
1547
+ itself.
1548
+
1549
+ ### Diverging maps take a center
1550
+
1551
+ ```tsx
1552
+ <Viz
1553
+ {...plot(rows, {x: "kd", y: "tm", color: "shift"})
1554
+ .point()
1555
+ .labs({headline: "Stability against the 60°C target"})
1556
+ .props()}
1557
+ fieldOverrides={FIELDS}
1558
+ palettes={palettesFor({diverging: "rdbu", center: 0})}
1559
+ />
1560
+ ```
1561
+
1562
+ <img src="docs/images/diverging.svg" width="520" alt="Points colored by Tm shift, red below the target and blue above">
1563
+
1564
+ State the center. A two-armed map puts its neutral at the domain's midpoint by default. A column of differences
1565
+ running from -2 to +18 then colors +8 as the neutral. `palettesFor` puts the center onto the `Palettes`, the layer
1566
+ build places a value symmetrically about it out to whichever arm reaches further, and equal distances from the middle
1567
+ take equally strong color on both sides. It defaults to zero. A color scale's own `center` states one per scale.
1568
+
1569
+ `rdbu`, `brbg` and `puor` are the ColorBrewer maps that stay legible under color-vision deficiency. Each diverging map
1570
+ runs its full span, which keeps the neutral centered.
1571
+
1572
+ ## Theme
1573
+
1574
+ Twelve custom properties, declared in `theme.css` with dark values under `.dark` and under a `prefers-color-scheme`
1575
+ query scoped to `:root:not(.light)`:
1576
+
1577
+ | Token | Surface or ink |
1578
+ | ------------------------- | ---------------------------------------------------------------------------------- |
1579
+ | `--viz-paper` | The page under the chart. Segment gaps and point halos take it |
1580
+ | `--viz-ink` | Geoms and the text on them |
1581
+ | `--viz-ink-muted` | Secondary strokes: whiskers, medians, joined runs |
1582
+ | `--viz-rule` | The axis rule, its ticks, and the rail behind an unselected category |
1583
+ | `--viz-annotation` | Annotation text written on the plot |
1584
+ | `--viz-leader` | Leader lines from an annotation to the geom it names |
1585
+ | `--viz-status-fail` | A threshold breach. Fixed, whichever palette is picked |
1586
+ | `--viz-status-warn` | A warning band, on the same terms |
1587
+ | `--viz-tooltip-bg` | The hover card's fill, the one surface the package paints. Dark under both schemes |
1588
+ | `--viz-tooltip-ink` | Values on the hover card |
1589
+ | `--viz-tooltip-ink-muted` | Labels and notes on the hover card |
1590
+ | `--viz-tooltip-ring` | The hover card's hairline edge |
1591
+
1592
+ `VIZ_TOKENS` lists the twelve, `TOKEN_MEANING` says what each paints, and `LIGHT_THEME` and `DARK_THEME` are the
1593
+ shipped values as a `ThemeSnapshot`, keyed by `VizToken`. A host with its own token layer declares the twelve in it,
1594
+ pointed at whatever it already calls them, and skips `theme.css`:
1595
+
1596
+ ```css
1597
+ :root {
1598
+ --viz-paper: var(--background);
1599
+ --viz-ink: var(--chart-ink);
1600
+ /* … */
1601
+ }
1602
+ ```
1603
+
1604
+ One block covers both themes. Each value resolves through `var()` where it is used, and the twelve follow their
1605
+ sources when the theme flips.
1606
+
1607
+ For the GPU path, which reads its colors as numbers:
1608
+
1609
+ ```ts
1610
+ import {resolveTheme, watchTheme, useVizTheme} from "@tetrascience-npm/ts-lib-viz/react";
1611
+
1612
+ const theme = useVizTheme(ref); // live snapshot, re-read where a value moved, null on the server
1613
+ const stop = watchTheme(element, (snapshot) => redraw(snapshot)); // a class, style or scheme change
1614
+ ```
1615
+
1616
+ `resolveTheme(element)` pushes each value through a probe element. Any color syntax a host writes arrives as `rgb()`.
1617
+
1618
+ ## The critic
1619
+
1620
+ `critique(spec, {exported?})` returns findings sorted worst first, in three severities taken from how Wilke labels his
1621
+ negative examples. `Viz` runs the checks that read the drawn frame as well and hands all of them to `onCritique`.
1622
+
1623
+ | Severity | Meaning |
1624
+ | -------- | ------------------------------------------------------------------------------------------------ |
1625
+ | `wrong` | Misstates the data. `blocking()` refuses the save until the author names the code in `overrides` |
1626
+ | `bad` | Warns |
1627
+ | `ugly` | Nudges |
1628
+
1629
+ Forty-one codes today. `FindingCode` is the union.
1630
+
1631
+ | Severity | Codes |
1632
+ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1633
+ | `wrong` | `grounded-nonlinear-axis`, `grounded-truncated-axis`, `cumulative-of-a-statistic`, `cumulative-unsupported`, `empty-as-zero-of-a-statistic`, `fixed-statistic`, `sides-under-facet`, `dendrogram-without-order`, `headline-missing`, `pie-not-parts`, `graph-links-dropped` |
1634
+ | `bad` | `color-alone`, `colors-past-legible`, `cluster-past-cap`, `track-group-disagrees`, `track-without-categories`, `marginal-without-readings`, `unlabeled-reference`, `bare-numeric-axis`, `headline-restates-axes`, `overplotted-past-switch`, `legend-missing`, `size-carries-the-measure`, `cube-copied-static`, `angle-encodes-comparison`, `slices-past-legible`, `bandwidths-disagree`, `ring-without-readings` |
1635
+ | `ugly` | `band-below-legible`, `numbers-below-legible`, `magnitudes-past-legible`, `figure-past-container`, `legend-order`, `title-over-numbers`, `set-repeats-form`, `set-opens-derived`, `size-past-fill-budget`, `single-value-as-arc`, `area-with-no-nesting`, `width-hides-the-count`, `shapes-past-glyphs` |
1636
+
1637
+ A `Finding` has its `severity`, its `code`, a `path` into the spec in the shape `validate` returns, such as
1638
+ `layers[0].aes.color`, and a `message` an author can act on. `exported: true` adds the checks a static copy draws,
1639
+ which today is a cube nobody can turn. The graph surface runs its own checks and reports them on the same contract.
1640
+
1641
+ ```tsx
1642
+ <Viz {...chart.props()} onCritique={(findings) => setFindings(findings)} />
1643
+ ```
1644
+
1645
+ ```ts
1646
+ import {critique, blocking} from "@tetrascience-npm/ts-lib-viz/core";
1647
+
1648
+ const stop = blocking(spec, critique(spec)); // the wrong findings no override waives, and a missing headline
1649
+ if (stop.length === 0) await save(spec);
1650
+ ```
1651
+
1652
+ `onCritique` fires when the findings change, and an arrow written inline settles. `overrides` takes a
1653
+ `WaivableCode`, each code but the `UnwaivableCode` `headline-missing`, and an overridden finding is admitted on the
1654
+ figure's own footer.
1655
+
1656
+ `grounded-nonlinear-axis`, `grounded-truncated-axis` and `fixed-statistic` read the grammar table's `proportional` and
1657
+ `aggregated` columns. A bar on a nonlinear axis and a fixed statistic come off the spec alone. All three run on the spec,
1658
+ which lets a server call the same function with the rows still in the database.
1659
+
1660
+ ### Footer counts
1661
+
1662
+ A cap the reader can see reads as a cap. What a build turns down lands in one ledger, and the footer line writes a
1663
+ clause for each kind of omission:
1664
+
1665
+ | Kind | Counts |
1666
+ | ----------------- | ----------------------------------------------- |
1667
+ | `panels` | Panels a facet dropped |
1668
+ | `categories` | Categories a band ranked past |
1669
+ | `splits` | Splits the split cap turned down |
1670
+ | `dashes` | Groups dashed as the first of several values |
1671
+ | `rows-sampled` | Rows past the line cap |
1672
+ | `stack` | A stack dropped over a negative reading |
1673
+ | `replicates` | Groups past the replicate cap |
1674
+ | `rows-incomplete` | Rows with a gap on a measure |
1675
+ | `segments` | Segments with a categorical end |
1676
+ | `off-log` | Readings at or below zero a log axis left off |
1677
+ | `off-root` | Readings below zero a square-root axis left off |
1678
+ | `off-range` | Readings stated limits censored |
1679
+ | `floored` | Intervals and whiskers cut at the axis floor |
1680
+ | `references` | Reference lines past their axis |
1681
+ | `rules` | Reference lines past the rule cap |
1682
+ | `measures` | Measures past the axis cap |
1683
+ | `flows` | Flows a sankey folded |
1684
+ | `links` | Links outside the drawn sectors |
1685
+ | `colors` | Sectors drawn in one ink past the color map |
1686
+ | `labels` | Labels a placement rule chose over |
1687
+
1688
+ ## Saved specs: `StoredSpec`, `loadSpec` and `SPEC_VERSION`
1689
+
1690
+ `ChartSpec` is the chart itself, and `StoredSpec` adds where a host keeps it: `source`, the `PlotSource` a plot reads
1691
+ (an `entity`, a `dataset`, a `lookup`, a `cohort` or a document `node`, by id), and `updatedAt`, which the host stamps.
1692
+ A host's own identity fields ride on its own subtype of `StoredSpec`:
1693
+
1694
+ ```ts
1695
+ import {loadSpec, plot, type StoredSpec} from "@tetrascience-npm/ts-lib-viz/core";
1696
+
1697
+ interface SavedFigure extends StoredSpec {
1698
+ projectId: string;
1699
+ }
1700
+
1701
+ const saved: SavedFigure = {...chart.spec(), source: {kind: "dataset", id: "campaign-7"}, projectId: "p-12"};
1702
+ await store.put(saved.id, JSON.stringify({...saved, updatedAt: Date.now()}));
1703
+
1704
+ const spec = loadSpec(JSON.parse(await store.get(id))); // a ChartSpec, migrated where it predates SPEC_VERSION
1705
+ ```
1706
+
1707
+ `spec()` writes `version: SPEC_VERSION`, and an absent version reads as the current format. `loadSpec(input)` takes
1708
+ JSON of unknown shape: a current spec comes back as it stands, a spec from before 0.1.2 migrates field by field, and a
1709
+ field the loader does not know rides through. It throws on another version, and on a document with no `id`, no layer
1710
+ list, or a layer with no `kind` and `aes`. [Migrating a saved spec](#migrating-a-saved-spec) lists what moves.
1711
+
1712
+ ## Profiles: the capability gate
1713
+
1714
+ One serializable profile, shared by the builder panel, the loader and the save path. A role sees one answer in three
1715
+ places:
1716
+
1717
+ ```ts
1718
+ import {validate, type CapabilityProfile} from "@tetrascience-npm/ts-lib-viz/core";
1719
+
1720
+ const analyst: CapabilityProfile = {
1721
+ id: "analyst",
1722
+ kinds: ["point", "line", "bar", "histogram"],
1723
+ aesthetics: {point: ["x", "y", "color"]},
1724
+ withhold: ["second-axis", "overrides", "side-panels"],
1725
+ limits: {layers: 4, annotations: 12},
1726
+ };
1727
+
1728
+ const verdict = validate(spec, analyst); // {ok, failures: [{path: "layers[1].kind", reason: "…"}]}
1729
+ ```
1730
+
1731
+ `kinds` and `aesthetics` are allowlists: absent allows each kind and each aesthetic the kind's geom table row binds,
1732
+ and a kind listed with a subset keeps its required aesthetics. `withhold` names the setting groups a role may not set.
1733
+ Each spec field is in one group, and a group a later version adds is open under a profile saved before it.
1734
+
1735
+ | `SettingGroup` | Spec fields |
1736
+ | -------------- | -------------------------------------------------------------------------------------------------------------- |
1737
+ | `log-scale` | A transform on a position scale |
1738
+ | `axis-range` | What the position scales span and mark: limits, breaks, ticks, formats, labels, band order and size, the coord |
1739
+ | `axis-chrome` | Rule width, tick length and side, label angle, title placement, type size, ink and grid |
1740
+ | `annotations` | Notes and axis-end captions |
1741
+ | `fits` | Fitted curves and smooths, with their confidence bands |
1742
+ | `facets` | Small-multiple grids |
1743
+ | `geom-style` | A layer's style constants and its position |
1744
+ | `labels` | Direct labels on geoms, and the numbers written in cells |
1745
+ | `second-axis` | A second vertical scale |
1746
+ | `figure-size` | The figure's width and height, the panel's aspect, the data's ratio, and the sizing |
1747
+ | `color-scale` | The color and fill maps past their titles, and the palette a layer names |
1748
+ | `legend` | Where the legends draw, and which layers reach them |
1749
+ | `side-panels` | Panels beside the plot area, and rings outside a circular figure |
1750
+ | `statistics` | A layer's aggregate, running total, statistic parameters, error bars and replicates |
1751
+ | `overrides` | Findings the author waived |
1752
+
1753
+ `id` names the profile and `label` is its display name. `limits` caps `layers` and `annotations`. `surfaces` names the
1754
+ drawing surfaces a role may author, `chart` or `graph`, apart from `kinds`: withholding a chart kind leaves the chart
1755
+ surface standing, and `validate` refuses a chart under a profile that withholds that surface. `OPEN_PROFILE` withholds
1756
+ nothing, and a `Verdict` lists each `Failure` by its dotted path.
1757
+
1758
+ ## Figure sets
1759
+
1760
+ A set pins color across the figures of one page. Color comes from first-seen order in each table by default. Plate P1
1761
+ draws at index 0 in a chart whose table met it first and index 1 in the next: Wilke's figures 21-7 and 21-8.
1762
+
1763
+ ```ts
1764
+ import {assign, critiqueSet, type FigureSet} from "@tetrascience-npm/ts-lib-viz/core";
1765
+
1766
+ let set: FigureSet = {assignments: {}, members: [{plotId: "overview"}, {plotId: "detail"}]};
1767
+ set = assign(set, "plate", ["P1", "P2", "P3"]); // {plate: {P1: 0, P2: 1, P3: 2}}
1768
+
1769
+ <Viz {...chart.props()} set={set} />;
1770
+ critiqueSet(set, {overview: specA, detail: specB});
1771
+ ```
1772
+
1773
+ `assignments` maps a field to a value to a categorical index, and `Viz` reads it. `assign` grows it at the save path
1774
+ and hands back the set it was given where nothing is new. `members` lists the figures in reading order, and
1775
+ `critiqueSet` reads it: `set-opens-derived` where the set opens on a statistic, and `set-repeats-form` where two
1776
+ adjacent members draw the same geometry off the same statistic. A host keeps its own name and id for a set on its own
1777
+ type.
1778
+
1779
+ ## Export
1780
+
1781
+ ```ts
1782
+ import {exportSvg, exportPng} from "@tetrascience-npm/ts-lib-viz/react";
1783
+
1784
+ const svg = exportSvg(figureElement); // tokens resolved to literals, on its own paper
1785
+ const bare = exportSvg(figureElement, {ground: false}); // for a caller compositing its own ground
1786
+ const png = await exportPng(figureElement, {scale: 2}); // a Blob, GL composited in the draw's own task
1787
+ ```
1788
+
1789
+ `exportSvg(root, {ground})` resolves the tokens and the font at export, and `ground`, on by default, paints the paper
1790
+ behind the figure. `exportPng(root, {scale})` draws at `scale` device pixels per CSS pixel, two by default. It
1791
+ composites the shared GL canvas's slice straight after the draw, in the same task, which lands a ten-million-geom cloud
1792
+ in the file. An export builds no renderer of its own.
1793
+
1794
+ ## Scale: the renderer switch thresholds
1795
+
1796
+ Rule 7's treatment switch reads a geom count, and the renderer and the footer read the one count, which keeps what
1797
+ draws and what the figure admits in agreement:
1798
+
1799
+ | Geoms | Treatment | Appearance |
1800
+ | --------------- | --------- | ---------------------------------------------------- |
1801
+ | up to 1,500 | `points` | One opaque geom per record |
1802
+ | 1,500 to 15,000 | `faded` | Opacity and radius drop and a cluster stays readable |
1803
+ | over 15,000 | `binned` | A density grid at pixel resolution, drawn on the GPU |
1804
+
1805
+ Where a substitution is in force the footer line states it. A reader looking at bins knows the geoms were counted.
1806
+ Hover costs a round trip there, and the footer line says so.
1807
+
1808
+ The renderer tier is a separate question from the treatment. One WebGL context serves the page. Each chart draws into
1809
+ its own scissored slice of it, which answers the browser's context cap. Positions upload center-relative and the GPU
1810
+ projects. A zoom moves two uniforms. Measured on the GPU's own clock: a million geoms runs at 120fps at any zoom, and
1811
+ ten million runs at 60fps from about four times zoomed in, where the cost becomes fill.
1812
+
1813
+ The renderer is asked for after mount. The first render draws the SVG treatment on a server and a client alike, and
1814
+ the GPU takes over once there is something to draw with.
1815
+
1816
+ By default the canvas covers the viewport and each chart is scissored to its own slice. A chart inside a dialog,
1817
+ inside a transformed parent, or inside a scroll container needs a canvas positioned against its own box, and
1818
+ `VizGlProvider` mounts one:
1819
+
1820
+ ```tsx
1821
+ import {VizGlProvider} from "@tetrascience-npm/ts-lib-viz/react";
1822
+
1823
+ <VizGlProvider>
1824
+ <Viz {...plot(rows, {x: "kd", y: "tm"}).point().labs({headline: "…"}).props()} />
1825
+ </VizGlProvider>;
1826
+ ```
1827
+
1828
+ It mounts its canvas as a child and positions it against its own box. A host with a canvas of its own passes a `Host`
1829
+ through the `host` prop, and `hostFor(canvas)` builds one from an element. A `Host` is the `canvas`, its `rect()` in
1830
+ page coordinates and its `dpr()`. Either way it stays one context, and the
1831
+ provider chooses which canvas that context draws into. `measure` times each frame on the GPU's clock, and `driven`
1832
+ leaves the frames to a host that calls `drawNow`.
1833
+
1834
+ `useGlRenderer()` returns the `GlRenderer` in force, or null: `available`, `schedule()`, `drawNow()` and `stats()`,
1835
+ which returns `FrameStats` or null. `FrameStats` is the submission cost as `Times`: `frames`, a count, with `p50`,
1836
+ `p95` and `max` in milliseconds, beside `gpu`, the same four off the GPU's clock, and `gpuProblem`, which says why
1837
+ `gpu` is null. `refreshGlSurface()` redraws each layer, for a host that moves its charts, and `releaseGlSurface()`
1838
+ drops the page renderer and its canvas.
1839
+
1840
+ Past what a client can process, aggregation belongs on a service. Run your own engine and hand the result in as rows,
1841
+ columns or an Arrow table for `toPlotData`.
1842
+
1843
+ ## `/builder`: the property column
1844
+
1845
+ `PlotPanel` is the column an author edits a spec through. It takes its colors and its table from the host, and it
1846
+ reads the same capability profile the loader and the save path read.
1847
+
1848
+ ```tsx
1849
+ import {PlotPanel} from "@tetrascience-npm/ts-lib-viz/builder";
1850
+
1851
+ <PlotPanel spec={spec} fields={table.fields} palettes={palettes} profile={analyst} onChange={setSpec} />;
1852
+ ```
1853
+
1854
+ | Prop | Type | Effect |
1855
+ | ---------- | ------------------------------- | ------------------------------------------------------------------------------------- |
1856
+ | `spec` | `S extends ChartSpec` | **Required.** The document, of the host's own spec type |
1857
+ | `fields` | `PlotField[]` | **Required.** The columns of the table the plot reads |
1858
+ | `onChange` | `(next: S) => void` | **Required.** Each edit, as a new spec of the host's type. The host stamps the time |
1859
+ | `palettes` | `Pick<Palettes, "categorical">` | **Required.** The layer colors the strip offers, the colors the chart beside it draws |
1860
+ | `sources` | `PlotSourceOption[]` | Tables the plot can point at. The picker reads and writes `StoredSpec.source` |
1861
+ | `profile` | `CapabilityProfile` | What this role may author. Unrestricted where absent |
1862
+ | `shape` | `ReactNode` | A summary of the table under the source picker, drawn by the host |
1863
+ | `findings` | `Finding[]` | Findings the host read off a built frame. Absent runs the spec-only checks |
1864
+
1865
+ The column runs Title, Data, Axes, Layers, Size, Hover and Annotations, and each section shows the findings whose path
1866
+ it edits. A withheld kind stays in the menu, grayed, with the reason on it. A withheld setting group grays in place,
1867
+ and its controls leave the tab order. The "Add layer" button adds the first kind the profile allows and stops at
1868
+ `limits.layers`. A `PlotSourceOption` is a `source` and its `label`, with an optional `hint` and the `columns` it
1869
+ offers.
1870
+
1871
+ This is the entry point that uses the UI kit, which is why it is apart from `/react`. Its **Size** section edits the
1872
+ figure's own `width`, `height` and `aspect` behind the `figure-size` group, and an org that fixes its figure sizes
1873
+ withholds one group and the controls gray in place.
1874
+
1875
+ ### `/builder` host requirements
1876
+
1877
+ The panel draws with Tailwind utilities over the kit's theme, the `--viz-*` status tokens, and six classes the host
1878
+ defines. A host does this on top of what a chart-only consumer does:
1879
+
1880
+ 1. Point Tailwind at the package, which generates the utilities the panel's markup names. Tailwind 3 takes a content
1881
+ glob, and Tailwind 4 takes an `@source` line in the stylesheet, relative to that stylesheet:
1882
+
1883
+ ```js
1884
+ content: ["./src/**/*.{ts,tsx}", "./node_modules/@tetrascience-npm/ts-lib-viz/dist/**/*.js"],
1885
+ ```
1886
+
1887
+ ```css
1888
+ @source "../node_modules/@tetrascience-npm/ts-lib-viz/dist";
1889
+ ```
1890
+
1891
+ 2. Define the six classes the panel asks for by name. `viz-control-field` is a form control at the host's own field
1892
+ height, `viz-h-control` matches it, `viz-size-control` is a square control of that height, `viz-press` is the
1893
+ active-state nudge, `viz-num` is tabular figures, and `viz-popover` is the settings surface.
1894
+ `demo/src/builder-skin.css` is a working reference written against the `--viz-*` tokens.
1895
+
1896
+ 3. Load the kit's theme, and declare `--viz-ink-muted`, `--viz-status-fail` and `--viz-status-warn`, which the panel's
1897
+ finding marks read.
1898
+
1899
+ With those in place the column takes the host's styling. Skip them and it falls back to browser defaults: white
1900
+ selects and native sliders.
1901
+
1902
+ ## `/graph`: the network surface
1903
+
1904
+ A physics network, on the context the charts own. cosmos moved to luma 9, which attaches to a context somebody else
1905
+ made, and the two surfaces can share one.
1906
+
1907
+ ```tsx
1908
+ import {GraphSurface} from "@tetrascience-npm/ts-lib-viz/graph";
1909
+
1910
+ <GraphSurface
1911
+ tables={{nodes, links, nodeValue: "degree"}}
1912
+ headline="Six teams, joined by two people each"
1913
+ width={520}
1914
+ height={420}
1915
+ palettes={palettesFor()}
1916
+ onCritique={setFindings}
1917
+ />;
1918
+ ```
1919
+
1920
+ | Prop | Type | Effect |
1921
+ | --------------- | ----------------------------------- | --------------------------------------------------------------------------------- |
1922
+ | `tables` | `GraphTables` | **Required.** The node and link tables, and the columns each role reads |
1923
+ | `headline` | `string` | **Required.** The claim the graph makes, the way a chart's is |
1924
+ | `width` | `number` | **Required.** Handed whole to the layout engine, which sizes its canvas off it |
1925
+ | `height` | `number` | **Required.** The same |
1926
+ | `palettes` | `Palettes` | **Required.** A graph reads in the same ink as the charts beside it |
1927
+ | `ownContext` | `boolean` | Whether the graph makes its own WebGL context. On by default |
1928
+ | `ground` | `boolean` | Whether the graph paints its own paper. Off by default |
1929
+ | `physics` | `GraphPhysics` | The forces. A field left absent takes the package's own value |
1930
+ | `display` | `GraphDisplay` | `pointScale`, `linkScale`, and `links` to draw or hide the links |
1931
+ | `layout` | `GraphLayout` | `force`, the default, or `fixed`, which pins each node at its `nodeX` and `nodeY` |
1932
+ | `paused` | `boolean` | Pauses the forces |
1933
+ | `focus` | `readonly string[]` | Node ids drawn in full. The rest draw in the muted ink at a low alpha |
1934
+ | `set` | `FigureSet` | Pins a group's color, as it pins a category on a chart |
1935
+ | `onSelect` | `(node: GraphNode \| null) => void` | The node clicked, and null where the click landed on the space around it |
1936
+ | `onHover` | `(node: GraphNode \| null) => void` | The node under the pointer, and null once the pointer leaves it |
1937
+ | `onContextMenu` | `(node: GraphNode \| null) => void` | A right-click on a node, or null on the space. A link hands nothing |
1938
+ | `onReady` | `(state) => void` | `{nodes, links, sharedContext}` once the graph draws, and after each data change |
1939
+ | `onCritique` | `(findings: Finding[]) => void` | Findings about the graph, on the contract a chart's use |
1940
+
1941
+ cosmos owns the layout, and the package owns the context, the frame clock, the tokens and the governance. `physics`
1942
+ reaches `gravity`, `repulsion`, `linkSpring`, `linkDistance`, `friction`, `decay` and `cluster`, and pulls a layout
1943
+ back where two escapees set the whole fit. Omit it for the package's own defaults, which suit a few hundred nodes where
1944
+ cosmos's suit tens of thousands. `cluster` pulls each node toward the middle of its group, and zero, the default, leaves
1945
+ the groups to the links.
1946
+
1947
+ `/graph` reads two tables and has its own entry point over the same three input shapes:
1948
+
1949
+ ```ts
1950
+ import {toGraphData} from "@tetrascience-npm/ts-lib-viz/graph";
1951
+
1952
+ const data = toGraphData({nodes, links, nodeId: "id", linkSource: "from", linkTarget: "to", linkValue: "calls"});
1953
+ data.linksDropped; // links naming a node the table does not hold
1954
+ ```
1955
+
1956
+ `GraphTables` names the columns: `nodeId`, `nodeLabel`, `linkSource`, `linkTarget`, `nodeValue` behind a node's color
1957
+ and `linkValue` behind a link's width, with `fieldOverrides` for their units. `nodeX` and `nodeY` place a node in their
1958
+ own units. They seed the force layout and pin a fixed one. `nodeGroup` names each node's group, and `tooltip` lists
1959
+ node columns the card adds after the value and the links. `GraphData` has `nodes` and `links`, the value
1960
+ ranges `valueDomain` and `linkValueDomain`, `groups` in first-seen order, `valueField` and `groupField` for the hover
1961
+ card's labels, and `linksDropped`. A `GraphNode` has its `id`, `label`, `value`, `group`, the `x` and `y` a table
1962
+ placed it at, and its `degree`. A `GraphLink` has a `source`, a `target` and a `value`.
1963
+
1964
+ ```tsx
1965
+ <GraphSurface
1966
+ tables={{nodes, links, nodeGroup: "cluster", nodeX: "umap_1", nodeY: "umap_2", tooltip: ["cdr3"]}}
1967
+ headline="Clusters stay apart under the kNN links"
1968
+ width={520}
1969
+ height={420}
1970
+ palettes={palettesFor()}
1971
+ physics={{cluster: 0.1}}
1972
+ focus={cohort}
1973
+ onContextMenu={(node) => setPicked(node?.id ?? null)}
1974
+ />
1975
+ ```
1976
+
1977
+ A node's color reads one source. A value takes the magnitude map, and a node with no value in a valued table takes the
1978
+ muted ink. `valueLimits` states the two ends the map spans, as a color scale's `limits` does, and a value past an end
1979
+ takes that end's color. A group takes the identity map, at the index a `set` pins or in first-seen order. A node with neither takes
1980
+ the first identity hue.
1981
+
1982
+ The surface is governed the way a chart is. A graph takes a `headline` at the type level, its findings block a
1983
+ published graph until it has a claim, and they block one whose links reached past the nodes the table has, which is
1984
+ the design language's line about a visible cap. A host reads a profile's `surfaces` before offering the graph.
1985
+
1986
+ ### One canvas serves one layout
1987
+
1988
+ The shared context costs the charts about a tenth of a millisecond. A million geoms reads 12.99 and 12.88 ms alone
1989
+ against 13.21 and 11.44 with a 2,000-node graph running on the same context. cosmos treats the whole canvas as its
1990
+ screen and moves the canvas into its own div, and on a shared context the graph draws across the page.
1991
+
1992
+ | | Contexts | Paneled | When |
1993
+ | --------------------- | -------- | ------- | ----------------------------------- |
1994
+ | own context (default) | two | yes | charts on the GPU beside it |
1995
+ | `ownContext={false}` | one | no | the graph is the page's GPU surface |
1996
+
1997
+ A graph asked to share refuses the lent canvas while a chart draws on it, and its message says to leave `ownContext`
1998
+ on. While cosmos is mid-clear, the frames queue until it finishes.
1999
+
2000
+ ## `/mcp`: the MCP server
2001
+
2002
+ `ts-lib-viz-mcp` is a stdio server an MCP client launches, and `/mcp` is the tool catalog and the drawing path under
2003
+ it. It runs in Node and draws through `react-dom/server` with no browser. One call returns a figure and its critic
2004
+ findings.
2005
+
2006
+ ```bash
2007
+ npx ts-lib-viz-mcp
2008
+ ```
2009
+
2010
+ Setup for Claude Desktop, Claude Code and other MCP clients is in [docs/mcp-setup.md](docs/mcp-setup.md).
2011
+
2012
+ The bin serves over `@modelcontextprotocol/sdk` and rasterizes through `@resvg/resvg-js`. Both are dependencies of the
2013
+ package and install with it. `/mcp` is Node only: its export condition is `node`, and a browser bundler resolves
2014
+ nothing there. `.mcp.json` in this repository registers the built copy for a client started here. The server reports
2015
+ the package's own version and offers four tools:
2016
+
2017
+ | Tool | Arguments | Returns |
2018
+ | ----------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
2019
+ | `describe_source` | `source` | Each column's id, label, role, unit and time scale, and the kinds the table can draw with the aesthetics each takes |
2020
+ | `create_plot` | `source`, `kind`, `aes`, `headline`, `layer`, `edits`, `theme` | A PNG, and the `ChartSpec` behind it with its findings and the codes a save gate refuses |
2021
+ | `edit_plot` | `source`, `spec`, `edits`, `theme` | The same, for the spec with the edits applied |
2022
+ | `render_plot` | `source`, `spec`, `theme`, `width`, `height`, `scale`, `format`, `path` | The spec redrawn as a PNG or an SVG, inline or written to a file |
2023
+
2024
+ A source is `{kind: "inline", rows}` or `{kind: "file", path}`. A file path resolves inside the server's working
2025
+ directory. A read takes a `.json`, `.csv` or `.tsv` file, and a write takes the extension of its format and leaves an
2026
+ existing file in place. `create_plot`'s `layer` takes flat constants such as `color`, `fill`, `linewidth` or `alpha`
2027
+ and settings such as `aggregate` or `position`, and a column binds through `aes`.
2028
+
2029
+ An edit set applies in one pass, in this order:
2030
+
2031
+ - `patch` merges chart-level fields onto the spec: `headline`, `subtitle`, `caption`, `facet`, `coord`, `scales`,
2032
+ `tooltip`, `annotations`, `legend`, `overrides`, `sides`, `width`, `height`, `aspect`, `ratio` and `sizing`. `scales`
2033
+ merges per aesthetic and then per field, which keeps `y.title` and `x` beside a new `y.limits`. `legend` and `facet`
2034
+ merge per field, an array or a scalar replaces, and a null clears its field.
2035
+ - `removeLayer` drops layers by id. Removing the last layer throws.
2036
+ - `addLayer` appends layers, each stating a `kind`, an `aes` of its own and flat options. A new layer inherits the aes
2037
+ of the first layer that reads the chart's rows and binds an x, and its id is its kind and the first free index, such
2038
+ as `point1`. `hline`, `vline` and `abline` take numbers as their flat positions, and a column binds through `aes`.
2039
+ - `bind` maps `{layer, aes, field}`. Omitting `layer` binds the first layer, and a null field unbinds.
2040
+
2041
+ `edit_plot` and `render_plot` read the client's spec through `loadSpec`. A spec saved before `SPEC_VERSION` migrates on
2042
+ the way in, and a malformed one fails at the tool boundary with a message naming the field. A faceted figure returns
2043
+ its spec and findings with the reason in place of the picture, because headless drawing covers one panel. A layer asking
2044
+ for a curve draws its geoms uncurved: the server passes no `Fitter`. `render_plot`'s `tokens` theme leaves each
2045
+ `--viz-*` token as a reference to itself and paints no ground, for a page that declares the theme, and it needs
2046
+ `format: "svg"`.
2047
+
2048
+ A host serving the tools from a server of its own imports them:
2049
+
2050
+ ```ts
2051
+ import {TOOLS, callTool} from "@tetrascience-npm/ts-lib-viz/mcp";
2052
+ ```
2053
+
2054
+ `/mcp` exports eight names. `TOOLS` is the catalog with each input schema, and `callTool(name, args)` runs one call by
2055
+ name and resolves to a `CallResult`, the image and text parts an MCP client reads as `content`. It throws on a failed
2056
+ call, and the bin answers that call with `isError: true`. `Edits` types an edit set. `renderSvg(options)` draws one
2057
+ panel to a standalone SVG string, and `renderPng(options)` draws it to a PNG, a `Uint8Array` beside the SVG, loading
2058
+ resvg at its first call. Importing `/mcp` for `renderSvg` loads no native addon. `RenderOptions` takes the `spec`, the
2059
+ `data`, and optionally `fieldOverrides`, `set`, `palettes`, `theme` (`light`, `dark` or `tokens`), `ground`, on unless
2060
+ the theme is `tokens`, and `scale` for the raster copy. A panel draws at the spec's size, 720 by 440 where it states
2061
+ none, and a faceted spec throws `MultiPanelFigure`.
2062
+
2063
+ ## Differences from ggplot2
2064
+
2065
+ The grammar takes ggplot2's name where the concept is the same. Six differences are deliberate:
2066
+
2067
+ | Here | ggplot2 | Why |
2068
+ | ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------- |
2069
+ | `band` on `smooth()`, `fit()`, `SmoothSpec` and `FitSpec` toggles the confidence band | `se` | The name says what draws. `level` keeps ggplot's name |
2070
+ | `thickness`, a width in pixels, on a bar, a histogram, a waterfall, a boxplot, a violin, an errorbar, a crossbar and a gauge's arc | `width`, a fraction of the axis's resolution | Screen lengths are pixels. `width` names the figure, a dodge and a jitter here |
2071
+ | A histogram stating neither `binwidth` nor `bins` takes the Freedman-Diaconis width | `stat_bin` defaults to 30 bins | The width follows the spread of the data. A `hex` lattice takes 30 a side, as ggplot's does |
2072
+ | `hex` draws hexagons, and `tiling: "rect"` draws squares | `geom_hex` and `geom_bin_2d` are two geoms | One kind and one statistic over two lattices |
2073
+ | `color` alone | `color` and its British spelling | One name per concept. The British spelling fails to compile at `plot()` and throws at a layer |
2074
+ | `halo`, in pixels, the paper-colored ring around a point | no counterpart | Space between overlapping points. A point takes no `linewidth` |
2075
+
2076
+ ## Migrating a saved spec
2077
+
2078
+ `loadSpec` reads a spec saved before 0.1.2. A document with `series` predates `SPEC_VERSION`, and each of its fields
2079
+ moves to today's name and shape:
2080
+
2081
+ - `series` becomes `layers` and `channels` becomes `aes`. The kinds take ggplot's names: `scatter` is `point`,
2082
+ `interval` is `ribbon`, `histogram2d` is `hex`, `box` is `boxplot` and `scatter3d` is `point3d`. A `range` layer
2083
+ takes the kind its `style.range` named, `pointrange` where it named none, and a `donut` becomes a `pie` with an
2084
+ `innerRadius` of 0.55.
2085
+ - The aesthetics take ggplot's names: `lo`, `hi` and `mid` are `ymin`, `ymax` and `y`, `xEnd` and `yEnd` are `xend`
2086
+ and `yend`, `opacity` is `alpha` and `dash` is `linetype`. A `color` column on a kind that maps `fill` and no color
2087
+ moves to `fill`.
2088
+ - `splitBy` moves to the layer's free paint aesthetic, or to `group`. A fit's or a smooth's `groupBy` moves to
2089
+ `group`. A numeric `bin` moves to `statParams.binwidth`, and a bar that stated one becomes a histogram.
2090
+ - The style keys: `opacity` is `alpha`, `stroke` splits into `color`, `linewidth` and `linetype`, `edgeWidth` is
2091
+ `halo`, `level` is `isoLevel`, a violin's `side` is `half`, a gauge's `bands` is `sections`, and a `jitter`
2092
+ becomes a jitter position at ggplot's default reach. A jitter position's stated `width` and `height` were shares of
2093
+ the resolution, and they drop to the same reach. A zero stays. On a kind with no interior, a stated `fill` is the
2094
+ `color`, ahead of the stroke's.
2095
+ - The chart fields: `dek` is `subtitle`, `fit` is `sizing`, and `facetBy` and `facetColumns` join `facet`. `coord`
2096
+ `rect` and `transpose` are `cartesian` and `flip`. `axes`, `colorScale` and the legend titles move into `scales`,
2097
+ with `range` as `limits`, `lineWidth` as `linewidth`, `tickStep` as `breakWidth`, a `log` or `sqrt` flag as `transform`,
2098
+ `scale` as `standardize`, the bin `breaks` as `bins`, and `legendTicks` as `breaks` and `labels`. A layer's `axis`
2099
+ `left` and `right` are `y` and `y2`. A side panel's `edge` is `position`, and its histogram's `bin` is `binwidth`.
2100
+ `aspect` inverts to height over width.
2101
+ - A layer's `label` rule is `directLabels`, and a top rule's `by` is `on`. A band order's `by` is `kind`, and its
2102
+ callback drops, because a function cannot survive a save.
2103
+ - A `reference` annotation becomes an `hline` or `vline` layer with its label. A `band`, a `callout` and a
2104
+ `series-label` drew nothing, and they drop.
2105
+ - A grouped bar, histogram or area that stated no position keeps its old overlap as `position: "identity"`.
2106
+
2107
+ A current spec comes back as it stands. One in this layout that states a position scale's `color` or `tickStep`, or a
2108
+ style's `side` or `bands`, takes `ink`, `breakWidth`, `half` or `sections`, and its `band`, `callout` and
2109
+ `layer-label` annotations drop. A field the loader does not know passes
2110
+ through, which keeps a host's own. No spec field names a statistic, and the statistic renames leave nothing to
2111
+ migrate.
2112
+
2113
+ ## Export map and full API
2114
+
2115
+ ```
2116
+ @tetrascience-npm/ts-lib-viz/core author, load, check and color a chart
2117
+ @tetrascience-npm/ts-lib-viz/react Viz, the toolbar types, the GPU provider, export, the theme hooks, the bar geometry
2118
+ @tetrascience-npm/ts-lib-viz/builder PlotPanel
2119
+ @tetrascience-npm/ts-lib-viz/graph GraphSurface, toGraphData, the physics knobs
2120
+ @tetrascience-npm/ts-lib-viz/mcp the MCP tools and server, headless SVG and PNG
2121
+ @tetrascience-npm/ts-lib-viz/theme.css the token values
2122
+ ```
2123
+
2124
+ Each entry point states its surface as a named list. Types come with each group:
2125
+
2126
+ | Entry point and group | Exports |
2127
+ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2128
+ | `/core` authoring | `plot`, `PlotBuilder`, `LayerOptions`, `LayerAes`, `LayerArgs`, `LayerCall`, `AnyLayerOptions`, `AnnotateValue`, `AnnotateValues`, `SmoothOptions`, `FitOptions`, `RuleOptions`, `RuleValue`, `Labs` |
2129
+ | `/core` the spec | `ChartSpec`, `StoredSpec`, `LayerSpec`, `Aes`, `Aesthetic`, `PlotKind`, `KINDS`, `LayerStyle`, `Linetype`, `PointShape`, `Aggregate`, `Position`, `PositionKind`, `ChartScales`, `PositionScale`, `ColorScale`, `GuideScale`, `AxisTransform`, `TickFormat`, `LegendOptions`, `Annotation`, `Anchor`, `Leader`, `LabelRule`, `LabelWhen`, `CellNumbers`, `StatParams`, `BandOrder`, `SidePanel`, `SideContent`, `FitSpec`, `SmoothSpec`, `SmoothMethod`, `PlotSource`, `PlotSourceOption` |
2130
+ | `/core` field types | `Parts`, `RingPanel`, `RingContent`, `LinkFields`, `PerAxis`, `BinClosed`, `BinDrop`, `Bandwidth`, `Kernel`, `QuantileType`, `ClusterDistance`, `Linkage`, `DepthScale` |
2131
+ | `/core` saved specs | `loadSpec`, `SPEC_VERSION` |
2132
+ | `/core` data | `toPlotData`, `fromRows`, `fromColumns`, `fromArrow`, `VizData`, `PlotData`, `PlotField`, `PlotFieldRole`, `FieldOverride`, `AdapterOptions`, `Arrayish`, `ArrowLike` |
2133
+ | `/core` critic | `critique`, `CritiqueOptions`, `blocking`, `Finding`, `FindingCode`, `Severity`, `WaivableCode`, `UnwaivableCode` |
2134
+ | `/core` profiles | `validate`, `CapabilityProfile`, `SettingGroup`, `Verdict`, `Failure`, `OPEN_PROFILE` |
2135
+ | `/core` fits | `Fitter`, `FitRequest`, `FitGroup`, `Fit`, `LayerFits`, `fitSignature` |
2136
+ | `/core` palettes | `PALETTES`, `registerPalette`, `Palette`, `PaletteName`, `palettesFor`, `PaletteChoice`, `Palettes`, `DEFAULT_PALETTES`, `DEFAULT_SEQUENTIAL`, `DEFAULT_DIVERGING`, `DEFAULT_CATEGORICAL`, `categoricalCss`, `sequentialCss`, `stopsOf` |
2137
+ | `/core` theme tokens | `VIZ_TOKENS`, `VizToken`, `TOKEN_MEANING`, `ThemeSnapshot`, `LIGHT_THEME`, `DARK_THEME` |
2138
+ | `/core` figure sets | `FigureSet`, `assign`, `critiqueSet` |
2139
+ | `/core` selection | `Selected`, `Brushed`, `BrushShape`, `Predicate`, `leaves` |
2140
+ | `/react` | `Viz`, `VizProps`, `ToolbarOptions`, `ToolbarItem`, `ToolbarView`, `exportSvg`, `SvgOptions`, `exportPng`, `PngOptions`, `useVizTheme`, `resolveTheme`, `watchTheme`, `VizGlProvider`, `VizGlProviderProps`, `useGlRenderer`, `GlRenderer`, `FrameStats`, `Times`, `Host`, `Rect`, `hostFor`, `refreshGlSurface`, `releaseGlSurface`, `MARK_RADIUS`, `roundedTop` |
2141
+ | `/builder` | `PlotPanel`, `PlotPanelProps` |
2142
+ | `/graph` | `GraphSurface`, `GraphSurfaceProps`, `GraphDisplay`, `GraphLayout`, `GraphPhysics`, `toGraphData`, `GraphData`, `GraphNode`, `GraphLink`, `GraphTables` |
2143
+ | `/mcp` | `TOOLS`, `callTool`, `CallResult`, `Edits`, `renderSvg`, `renderPng`, `RenderOptions`, `MultiPanelFigure` |
2144
+
2145
+ ### Stability
2146
+
2147
+ Each name above is semver surface from 0.1.2. A name these lists leave out is internal, and the
2148
+ exports map keeps it out of reach.
2149
+
2150
+ The unions a consumer receives are open, and a minor release may add a member to any of them.
2151
+ They are the union fields of the `ChartSpec` that `spec()`, `loadSpec` and the `PlotPanel` change
2152
+ callback hand back, and the unions a callback or a `Fitter` receives. The ones a reader switches on
2153
+ most are `FindingCode`, `Severity`, `Selected.kind`, `Predicate.kind`, `FitSpec.model`,
2154
+ `SmoothMethod`, `PlotKind`, `Aggregate`, `AxisTransform`, `TickFormat`, `PointShape`, `Linetype`,
2155
+ `Annotation.kind` and `SideContent.kind`. A switch over one keeps a default branch. A predicate
2156
+ compiler that meets a kind it does not know refuses the filter and says so, which keeps a dropped
2157
+ filter from reading as a match.
2158
+
2159
+ ## Design language
2160
+
2161
+ `CHART-DESIGN.md` in this repository is the opinion the package enforces: eleven rules arranged by
2162
+ the grammar component each one constrains, cited by number from docstrings across `src/`. Read it
2163
+ before adding a geom or changing a default. Rules 7, 8, 10 and 11 have code behind them today: the
2164
+ renderer switch, the color sources, the type scale with the claim it asks for, and proportional ink.
2165
+
2166
+ Its coordinates passage states the condition the cube rests on. A third position scale is allowed
2167
+ where the reader can rotate and the chart shows depth cues.
2168
+
2169
+ ## Contributing
2170
+
2171
+ Setup, the scripts, the demo app, the tests that check this README against the exports, and the review flow are in
2172
+ [CONTRIBUTING.md](CONTRIBUTING.md).