plotagents 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/AGENTS.md +98 -0
  2. package/LICENSE +21 -0
  3. package/README.md +217 -2
  4. package/bin/plotagents.js +73 -0
  5. package/dist/plotagents-geo.js +79 -0
  6. package/dist/plotagents.js +11611 -0
  7. package/docs/api.md +172 -0
  8. package/docs/charts.md +352 -0
  9. package/docs/colorscales.md +46 -0
  10. package/docs/dashboards.md +79 -0
  11. package/docs/getting-started.md +142 -0
  12. package/docs/rendering.md +47 -0
  13. package/docs/themes.md +116 -0
  14. package/index.d.ts +384 -0
  15. package/package.json +80 -4
  16. package/schema.json +1874 -0
  17. package/src/axes.js +152 -0
  18. package/src/charts/bar.js +350 -0
  19. package/src/charts/categorical.js +495 -0
  20. package/src/charts/chord.js +218 -0
  21. package/src/charts/choropleth.js +807 -0
  22. package/src/charts/dist.js +530 -0
  23. package/src/charts/donut.js +232 -0
  24. package/src/charts/flowchart.js +407 -0
  25. package/src/charts/gantt.js +460 -0
  26. package/src/charts/heatmap.js +76 -0
  27. package/src/charts/kpi.js +100 -0
  28. package/src/charts/line.js +551 -0
  29. package/src/charts/network.js +707 -0
  30. package/src/charts/pointmap.js +599 -0
  31. package/src/charts/pyramid.js +177 -0
  32. package/src/charts/radar.js +158 -0
  33. package/src/charts/regplot.js +370 -0
  34. package/src/charts/sankey.js +169 -0
  35. package/src/charts/scatter.js +214 -0
  36. package/src/charts/sunburst.js +136 -0
  37. package/src/charts/treemap.js +197 -0
  38. package/src/charts/wordcloud.js +163 -0
  39. package/src/colorscales.js +182 -0
  40. package/src/context.js +10 -0
  41. package/src/dashboard.js +438 -0
  42. package/src/dashed.js +90 -0
  43. package/src/data.js +137 -0
  44. package/src/facet.js +84 -0
  45. package/src/format.js +203 -0
  46. package/src/frame.js +226 -0
  47. package/src/geo/chile.js +7 -0
  48. package/src/geo/data/chile-regiones.js +12 -0
  49. package/src/geo/data/usa-estados.js +12 -0
  50. package/src/geo/data/world.js +12 -0
  51. package/src/geo/projection.js +217 -0
  52. package/src/geo/registry.js +110 -0
  53. package/src/geo/usa.js +8 -0
  54. package/src/geo/world.js +7 -0
  55. package/src/hierarchy.js +139 -0
  56. package/src/index.js +336 -0
  57. package/src/infer.js +58 -0
  58. package/src/interact.js +483 -0
  59. package/src/lint.js +417 -0
  60. package/src/palette.js +59 -0
  61. package/src/runtime.js +416 -0
  62. package/src/scale.js +241 -0
  63. package/src/schema.js +337 -0
  64. package/src/stats.js +303 -0
  65. package/src/svg.js +85 -0
  66. package/src/text.js +61 -0
  67. package/src/theme.js +311 -0
package/AGENTS.md ADDED
@@ -0,0 +1,98 @@
1
+ # plotagents · guide for AI agents
2
+
3
+ One function, one JSON object. No design decisions: the library makes them.
4
+
5
+ ```js
6
+ import { plot, safePlot } from 'plotagents';
7
+ const svg = plot({ type, data, x, y, series, title, subtitle, source });
8
+ ```
9
+
10
+ ## Rules for a good chart
11
+
12
+ 1. **`title` is the finding**, a full sentence with the key number: "Biobío accounts for 30% of sales", not "Sales by region".
13
+ 2. **`subtitle` says how to read it**: measure, unit and period.
14
+ 3. **Always set `source`.** If the data is made up, use `source: "illustrative data"`.
15
+ 4. `data` is a list of rows (`[{ region: "Biobío", sales: 1240 }]`). For a wide table, pass `y: ["revenue", "costs"]`.
16
+ 5. Call `safePlot(spec)` as your tool: it never throws and returns `errors`, `warnings` and `suggestions`, each with a `fix`. If `ok` is `false`, fix the spec and call again.
17
+ 6. Set `locale: "en"` for English number formats (default is Spanish: `1.234,5`).
18
+
19
+ ## Which type
20
+
21
+ | To show | `type` | Key fields |
22
+ |---|---|---|
23
+ | Compare categories | `bar` | `x`, `y`, `series?`, `stack?` (`true` / `"percent"`), `top?` |
24
+ | Count rows per category | `countplot` | `x` |
25
+ | Mean per category with a CI | `barplot` or `point` | `x`, `y`, `hue?` |
26
+ | Change over time | `line` | `x` date (`"2024-03"`) or year, `y`, `series?`; `ci: true` with several observations per x |
27
+ | A project plan or schedule | `gantt` | `task`, `start`, `end` (or `duration`), `group?`, `progress?`, `dependsOn?`, `today?`, `collapsed?` |
28
+ | Volume over time | `area` | like `line`; stacks with `series` |
29
+ | Measures on different scales | `line` + `index: true`, or `facet` | **there is no dual axis** |
30
+ | Exponential growth | `line` + `yScale: "log"` | |
31
+ | Relationship between two measures | `regplot` (fit + CI) / `scatter` / `bubble` | `x`, `y`, `hue?`, `size?`, `label?` |
32
+ | Relationship + marginals | `jointplot` | `x`, `y` |
33
+ | Distribution of one measure | `hist` (`kde: true`), `kde`, `ecdf` | `x`, `hue?` |
34
+ | Distribution by category | `box`, `violin`, `strip`, `swarm` | `x` category, `y` measure, `hue?` |
35
+ | Multi-dimensional profile | `radar` | `axis`, `value`, `series` (≤ 4 series) |
36
+ | Hierarchical part-to-whole | `treemap` or `sunburst` | `path: [level1, level2, …]`, `value` |
37
+ | Part-to-whole, ≤ 6 parts | `donut` / `pie` | `label`, `value`; `half: true` for a semicircle |
38
+ | Magnitude on a grid | `heatmap` | `x`, `y`, `value` |
39
+ | A value per region, state or country | `choropleth` (`symbolmap` for totals) | `geo: "chile" \| "usa" \| "world"` or any GeoJSON/TopoJSON object, `key`, `value` (text → one color per category) |
40
+ | Dots at real places on a street map | `pointmap` | `lon`, `lat` (auto-detected), `size?`, `hue?`, `value?`, `label?`; `tiles: "osm"` (default) / `"esri-gray"` / `"esri-dark"`, or carto-* / mapbox-* with `tilesKey` |
41
+ | Who is connected to whom | `network` | edges `from`, `to`, `value?`; `nodes?` with `group`; `layout?` |
42
+ | Exchanges between a few groups | `chord` | `from`, `to`, `value` |
43
+ | Age structure | `pyramid` | `age`, `sex`, `value` |
44
+ | A process with decisions | `flowchart` | `nodes` (`type`, `lane`), `edges` (`label`) |
45
+ | Flows between stages | `sankey` | `from`, `to`, `value` |
46
+ | One or more numbers | `kpi` | `items: [{ label, value, delta, period, trend, target, good }]` |
47
+ | What comes up most in text | `wordcloud` | `text` (field or raw text), `value?`, `series?`; prefer `bar` + `top` to compare exactly |
48
+
49
+ seaborn names work (`histplot`, `kdeplot`, `boxplot`, `violinplot`, `lmplot`, `stripplot`, `swarmplot`, `pointplot`), and `hue` is an alias of `series`. Leave `type` out to infer it from the data.
50
+
51
+ ## Most useful options
52
+
53
+ - `highlight: "Ñuble"`: emphasize one category or series and mute the rest. `exclude: ["Maule"]` drops entries and recomputes the chart; colors stay put.
54
+ - `legend: "top" | "bottom" | "left" | "right" | false`: where the legend goes (top by default).
55
+ - `colorScale: "viridis"`: any matplotlib colormap for heatmaps, maps and treemaps by change (`"RdBu"` diverges around 0; `_r` reverses; or a list of colors). `palette: "tab10"` for categories.
56
+ - `dashed` for what is not a firm number (estimates, projections, provisional figures): a name, a list, or a data field (`dashed: "provisional"`). Shapes keep their color, with a hatched fill and a dashed outline. On a time axis, `dashedFrom: 2025` dashes lines, areas and columns from that year on. **Always set `dashedLabel`** ("Projection", "Preliminary") so readers know what the hatching means.
57
+ - `facet: "region"` (+ `columns`): one panel per value, on a shared scale.
58
+ - `time: "year"`: one period at a time (the latest) with % change vs the previous one. Time controls are **off by default**: add `slider: true` only when the person asks to move through periods (buttons for ≤ 8 periods, a minimal slider otherwise; `"buttons"` / `"slider"` force one, `play: false` hides play). Treemaps can be colored by change with `colorBy: "change"`.
59
+ - `refLines: [{ y: 600, label: "Target" }]` and `annotations: [{ x: "2024-01", label: "New branch" }]`.
60
+ - `format: "percent" | "currency" | "compact" | "integer"` or `{ prefix, suffix, decimals }`.
61
+ - `xScale` / `yScale: "log"`.
62
+ - `theme: "noche"` or a JSON object (`{ extends, categorical, type, marks, font }`); `palette: [...]` for your own colors.
63
+ - `font: "Poppins"` and `textScale: 1.5` (presentation mode); `configure({ font, textScale })` sets them for every chart.
64
+ - `network` + `focus: "node id"`: center a node and highlight its neighbors.
65
+ - Your own map: `geo: <GeoJSON or TopoJSON>`; the matching property is found for you (`featureKey` to force it). Add `markers: [{ lon, lat, label }]`, `layers: [{ geo, label }]` for rivers or routes, and `fitTo: ["Biobío"]` or a `[lonMin, latMin, lonMax, latMax]` box to zoom.
66
+ - `gantt`: day `end` dates are inclusive; a row without `end` is a milestone. Always set `today` on a live plan. `collapsed: ["Phase 2"]` (or `true`) folds phases into one summary bar; in the browser a click on a phase toggles it.
67
+ - `network` + `layout: "force" | "circular" | "radial" | "concentric" | "clusters" | "tree" | "grid"` picks the placement; `curveness: 0` straightens edges.
68
+ - `pointmap` draws on OpenStreetMap tiles by default (`tiles: "esri-gray"`, `"mapbox-light"` + `tilesKey`, or your own `{ url, attribution }`). Tiles load only when the SVG is inline or in `toHTML`, not inside `<img>`.
69
+ - Your own look for every chart: `registerTheme("acme", { background, text, grid: { color, dash }, categorical: "tab10", font })` then `configure({ theme: "acme" })`.
70
+ - `geo: "usa"`: states match by postal code ("TX"), English or Spanish name, or FIPS ("48"). Alaska and Hawaii are insets; Puerto Rico appears only when your data has it. In the browser, maps zoom on click, Ctrl/⌘ + scroll or pinch.
71
+
72
+ ## Mistakes the library already handles
73
+
74
+ - More than 8 series → the 9th onward turn gray; `lint` suggests `highlight` or `facet`.
75
+ - Colliding line labels → spread apart with leader lines.
76
+ - Donut with more than 6 parts → folds into "Other".
77
+ - Long category labels → switches to horizontal.
78
+ - Hard-to-tell custom palette → `lint` names the offending pair.
79
+ - Numbers as text ("1.234,5", "12%", "$ 3.000") → parsed automatically.
80
+ - Tens of thousands of points → drawn as batched paths, still fast.
81
+
82
+ ## Dashboards
83
+
84
+ When someone asks for a dashboard, call `safeDashboard({ title, subtitle, source, data, kpis, charts, filters })` (tool: `toolDefinition({ kind: 'dashboard' })`). Layout, widths, shared colors and filters are decided for you:
85
+
86
+ - `title` is the **question** the dashboard answers; every chart still gets its finding as title.
87
+ - At most **5 KPIs**, computed from `data` when possible: `{ label, field, agg: "sum", compare: { field: "year", current: 2025, previous: 2024 }, trendBy: "month" }`.
88
+ - **4–6 charts**. The first time series (or the one with `primary: true`) goes full width; the rest fill balanced rows.
89
+ - `filters: ["region", "channel"]` become buttons that filter every chart and KPI.
90
+ - No more than one donut; one `source` for the page.
91
+
92
+ ## Outputs
93
+
94
+ - `plot(spec)` → SVG string. Drop it into HTML, Markdown, an `.svg` file or a PDF.
95
+ - `toHTML([spec1, spec2])` → self-contained page with tooltips, sliders and drill-down.
96
+ - `describe(spec)` → alt text for the chart.
97
+ - `schema` / `toolDefinition()` → JSON Schema and tool definition (Anthropic or OpenAI).
98
+ - CLI: `npx plotagents spec.json -o chart.svg`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Navarrete
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,218 @@
1
- # Temporary Holding Version
1
+ # plotagents
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
+ **Beautiful charts from a single JSON spec, built for AI agents.**
4
+
5
+ **[Documentation, live examples and playground →](https://carlosnavarrete.cl/plotagents/)**
6
+
7
+ Data and field names go in; an accessible SVG comes out, with careful typography, colorblind-safe colors and tooltips. 34 chart types: the ones people reach for in seaborn, multi-level treemaps and sunbursts, choropleth maps of Chile, the United States and the world, networks, chord diagrams, population pyramids, flow charts and Gantt charts, plus word clouds, a dashboard builder with best-practice layouts, opt-in time controls, small multiples and fully JSON-configurable themes. Zero dependencies. Runs in Node, Deno, Bun and the browser.
8
+
9
+ ```bash
10
+ npm install plotagents
11
+ ```
12
+
13
+ ```js
14
+ import { plot } from 'plotagents';
15
+
16
+ const svg = plot({
17
+ title: 'Biobío accounts for 30% of southern sales',
18
+ subtitle: 'Sales by region, CLP millions, 2025',
19
+ source: 'illustrative data',
20
+ data: [
21
+ { region: 'Biobío', sales: 1240 },
22
+ { region: 'Araucanía', sales: 880 },
23
+ { region: 'Ñuble', sales: 610 },
24
+ ],
25
+ x: 'region',
26
+ y: 'sales',
27
+ locale: 'en',
28
+ });
29
+ ```
30
+
31
+ ![Columns](examples/svg/barras.svg)
32
+
33
+ The [interactive gallery](https://carlosnavarrete.cl/plotagents/examples/), 61 charts with the code for each one, is also in [`examples/index.html`](examples/index.html). Try any spec live in the [playground](https://carlosnavarrete.cl/plotagents/playground/).
34
+
35
+ ## Why
36
+
37
+ Agents are good at data and bad at charts: dual axes, 12-slice pies, titles that say nothing. plotagents takes design decisions out of the agent's hands. The rules come from data-visualization teaching for management (Wilke's *Fundamentals of Data Visualization*, the Data Viz Catalogue, the Atlas of Economic Complexity) and are written into the code:
38
+
39
+ - **The title states the finding.** `lint` nudges toward it and `describe` writes the alt text.
40
+ - **One axis.** There is no dual axis; `index: true` rebases series to 100 and `facet` draws panels on a shared scale.
41
+ - **Labels at the end of every line**, always. When they collide they are spread apart and joined to their point by a thin leader line; a legend appears only when needed.
42
+ - **Every pixel for the data.** The y axis sits inside the plot on its gridline; margins and type scale down on phones; treemaps, sunbursts, horizontal bars, heatmaps and KPI tiles size their own height.
43
+ - **Color follows the entity.** Eight validated colors in a fixed order; "Copper" keeps its color when you filter, drill down or move through periods. One solid color per category.
44
+ - **Legend and chart are connected.** Hover a legend key to light up its marks, click to pin, shift + click to drop that entry (axes and shares recompute, colors stay put). In treemaps a click zooms the whole plot to the category. The legend goes top by default, or `legend: "bottom" | "left" | "right"`.
45
+ - **Tooltips that never cover the title.** They sit next to the hovered mark, stay inside the chart, and their header wears the mark's color with white or dark text picked by contrast. Arrow keys walk through the data.
46
+ - **Estimates look like estimates.** `dashed` hatches the shapes that are projections or provisional figures (same color, striped fill, dashed outline) and `dashedFrom: 2025` turns lines, areas and columns dashed from that point on, over a soft labeled band. The legend says what the hatching means; hovering it lights up just those shapes.
47
+ - **Maps you can explore.** Click a state or region to zoom to it, Ctrl/⌘ + scroll or pinch to zoom, drag to pan; +/−/reset buttons for the keyboard. Hovering outlines the shape instead of dimming the map, and each color class in the legend lights up its regions. Moving through years, colors glide from one to the next.
48
+ - **Networks you can explore.** Curved edges in the source node's color, sized nodes and labels that never pile up. Pick the placement with `layout` (force, circular, radial, concentric, clusters, tree, grid). Click a node and it glides to the center with its connections highlighted; click again or press Esc to go back.
49
+ - **Thin marks, quiet grid.** 4 px rounded data ends, 2.25 px lines, 2 px surface gaps instead of borders.
50
+ - **Locale-aware numbers.** Spanish (Chile) by default: `1.234,5`, `56,1%`, `$18.500`. `locale: 'en'` gives `1,234.5`.
51
+
52
+ ## Chart types
53
+
54
+ | Purpose | `type` (aliases) |
55
+ |---|---|
56
+ | Compare categories | `bar` (`barplot` with confidence intervals), `count` (`countplot`) |
57
+ | Change over time | `line` (`lineplot`, `ci` for a confidence band), `area` |
58
+ | Relationships | `scatter`, `bubble`, `regplot` (`lmplot`), `residplot`, `jointplot` |
59
+ | Profiles | `radar` (`spider`) |
60
+ | Distributions | `hist` (`histplot`), `kde` (`kdeplot`), `ecdf`, `box` (`boxplot`), `violin`, `strip`, `swarm` (`beeswarm`), `point` (`pointplot`) |
61
+ | Part-to-whole | `treemap` (any depth, with % change over time), `sunburst`, `donut`, `pie` |
62
+ | Maps | `choropleth` (Chile by region, US by state, world by country, or your own GeoJSON / TopoJSON with markers, layers and framing), `symbolmap`, `pointmap` (lat/lon dots over OpenStreetMap or Mapbox tiles) |
63
+ | Projects | `gantt` (`timeline`, `roadmap`): phases that fold and unfold, progress, milestones, dependencies and a today line |
64
+ | Networks and flows | `network`, `chord`, `sankey`, `flowchart` (with swimlanes) |
65
+ | Populations | `pyramid` |
66
+ | Grids | `heatmap` |
67
+ | Numbers | `kpi` |
68
+ | Text | `wordcloud` (words sized by frequency, or raw text to count) |
69
+ | Dashboards | `dashboard({ title, kpis, charts, filters })`: a whole HTML dashboard with best-practice layout ([guide](docs/dashboards.md)) |
70
+
71
+ Leave `type` out and it is inferred: dates → `line`, two measures → `scatter`, `source`/`target` → `sankey`, `path` → `treemap`, categories → `bar`. Every option is documented in [`docs/charts.md`](docs/charts.md).
72
+
73
+ | | | |
74
+ |---|---|---|
75
+ | ![](examples/svg/lineas.svg) | ![](examples/svg/treemap-niveles.svg) | ![](examples/svg/regresion.svg) |
76
+ | ![](examples/svg/violin.svg) | ![](examples/svg/sunburst.svg) | ![](examples/svg/histograma.svg) |
77
+ | ![](examples/svg/radar.svg) | ![](examples/svg/sankey.svg) | ![](examples/svg/conjunto.svg) |
78
+ | ![](examples/svg/mapa-chile.svg) | ![](examples/svg/cuerdas.svg) | ![](examples/svg/piramide.svg) |
79
+
80
+ ## Time, panels and drill-down
81
+
82
+ ```js
83
+ // One period at a time (the latest). Controls are opt-in: `slider: true` adds
84
+ // period buttons (few periods) or a minimal slider (many), with a play button.
85
+ plot({ type: 'treemap', data, path: ['sector', 'product'], value: 'value', time: 'year', slider: true });
86
+
87
+ // Time series: `slider: true` adds a two-handle range in the browser.
88
+ render('#chart', { type: 'line', data, x: 'month', y: 'sales', series: 'region', slider: true });
89
+
90
+ // Small multiples (seaborn's col / col_wrap) with shared scales and colors.
91
+ plot({ type: 'area', data, x: 'month', y: 'sales', facet: 'region', columns: 3 });
92
+
93
+ // Treemaps and sunbursts of any depth; click a group to drill down.
94
+ plot({ type: 'sunburst', data, path: ['area', 'unit', 'item'], value: 'amount', focus: ['Teaching'] });
95
+
96
+ // Log scales with 1-2-5 ticks and no empty decades.
97
+ plot({ type: 'line', data, x: 'month', y: 'users', series: 'platform', yScale: 'log' });
98
+ ```
99
+
100
+ ## One switch for fonts and text size
101
+
102
+ ```js
103
+ import { configure } from 'plotagents';
104
+
105
+ configure({ font: 'Poppins', textScale: 1.5 }); // every chart from now on
106
+ plot({ ...spec, textScale: 2 }); // or per chart: presentation mode
107
+ configure(null); // back to defaults
108
+ ```
109
+
110
+ `font` takes a Google Fonts name (it is loaded for you in the browser and in `toHTML()`), a CSS stack or `{ family, import }`. `textScale` multiplies every text size and the layout is recomputed with the real sizes, so labels at ×2 still never overlap. `configure()` also accepts `locale`, `theme`, `palette` or any other spec option.
111
+
112
+ ## Themes are JSON
113
+
114
+ Everything visual is a JSON object merged over a base theme, so an agent can apply a brand without touching code. See [`docs/themes.md`](docs/themes.md).
115
+
116
+ ```js
117
+ plot({
118
+ ...spec,
119
+ theme: {
120
+ extends: 'papel', // or 'noche' (dark)
121
+ categorical: 'okabe-ito', // palette name or a list of colors in fixed order
122
+ surface: '#FFFFFF',
123
+ font: { family: "'Poppins', sans-serif" },
124
+ type: { title: 22, titleWeight: 700 },
125
+ marks: { lineWidth: 3, barRadius: 8, barMax: 44 },
126
+ axes: { inside: false },
127
+ },
128
+ });
129
+ ```
130
+
131
+ Register it once and every chart uses it; the default look never changes unless you ask:
132
+
133
+ ```js
134
+ registerTheme('acme', { background: '#FFF', text: '#111827', grid: { color: '#EEF0F4', dash: '2 3' }, categorical: 'tab10', font: 'Inter' });
135
+ configure({ theme: 'acme' });
136
+ ```
137
+
138
+ Every matplotlib colormap works by name for heatmaps, maps and treemaps by change: `colorScale: 'viridis'`, `'RdBu_r'`, or your own list of colors ([color scales](docs/colorscales.md)).
139
+
140
+ `validatePalette(colors)` checks a custom palette with the same tests the built-in one passed (lightness band, chroma floor, colorblind separation, normal-vision separation), and `lint` runs it for you.
141
+
142
+ ## SVG, not Canvas
143
+
144
+ plotagents renders SVG. Dense charts (more than 1,500 points) are drawn automatically as one path per color, with a nearest-point tooltip layer, which paints faster than Canvas while keeping vector output, server-side rendering and accessible text. The benchmark and the reasoning are in [`docs/rendering.md`](docs/rendering.md).
145
+
146
+ | Points | SVG, one node per point | Canvas | plotagents (batched SVG) |
147
+ |---|---|---|---|
148
+ | 5,000 | 62 ms | 30 ms | 12 ms |
149
+ | 20,000 | 671 ms | 100 ms | 38 ms |
150
+ | 50,000 | 1,468 ms | 357 ms | 123 ms |
151
+
152
+ ## API
153
+
154
+ ```js
155
+ import { plot, safePlot, lint, describe, render, toHTML, schema, toolDefinition, validatePalette } from 'plotagents';
156
+ ```
157
+
158
+ | Function | Returns |
159
+ |---|---|
160
+ | `plot(spec)` | SVG string. Throws `PlotError` with a fix hint. |
161
+ | `safePlot(spec)` | `{ ok, svg, description, errors, warnings, suggestions }`. Never throws. |
162
+ | `lint(spec)` | Review of the spec without drawing: errors and design suggestions. |
163
+ | `describe(spec)` | Alt text ("Highest: Biobío with 1,240 (30%)…"). |
164
+ | `render(el, spec)` | Browser: tooltips, responsive width, drill-down, and time controls when the spec asks for them. |
165
+ | `toHTML(specs)` | A self-contained, interactive HTML page in one file. |
166
+ | `schema` / `toolDefinition({ flavor })` | JSON Schema of the spec and a tool definition for Claude (`anthropic`) or OpenAI (`openai`). |
167
+ | `validatePalette(colors, opts)` | `{ ok, checks }`. |
168
+
169
+ In the browser without a bundler, `<script src="dist/plotagents.js"></script>` defines `window.plotagents`. Full types are in [`index.d.ts`](index.d.ts) and every option in [`schema.json`](schema.json).
170
+
171
+ ## As an agent tool
172
+
173
+ ```js
174
+ import Anthropic from '@anthropic-ai/sdk';
175
+ import { safePlot, toolDefinition } from 'plotagents';
176
+
177
+ const client = new Anthropic();
178
+ const res = await client.messages.create({
179
+ model: process.env.ANTHROPIC_MODEL, // the model you use
180
+ max_tokens: 4096,
181
+ tools: [toolDefinition()],
182
+ messages: [{ role: 'user', content: 'Plot the distribution of service times per clinic: …' }],
183
+ });
184
+ const call = res.content.find((b) => b.type === 'tool_use');
185
+ const { ok, svg, errors, suggestions } = safePlot(call.input);
186
+ // If !ok, send `errors` back as the tool_result: every error carries a `fix`.
187
+ ```
188
+
189
+ [`AGENTS.md`](AGENTS.md) is a short guide meant to be pasted into an agent's system prompt.
190
+
191
+ ## CLI
192
+
193
+ ```bash
194
+ npx plotagents spec.json -o chart.svg # SVG
195
+ npx plotagents specs.json -o report.html # several interactive charts on one page
196
+ npx plotagents spec.json --lint # review and suggestions
197
+ npx plotagents --tool # tool definition
198
+ ```
199
+
200
+ ## Built-in palette
201
+
202
+ | Theme | Surface | Categorical (fixed order) |
203
+ |---|---|---|
204
+ | `papel` | `#FCFBF9` | `#3A47B8` `#D42A5E` `#E8A33D` `#1E9C89` `#7B5CD6` `#B5562E` `#5BA3E0` `#8E9A2F` |
205
+ | `noche` | `#0B0F2B` | `#6170E0` `#E63369` `#C4851C` `#22A892` `#9780E8` `#D06A3E` `#499BDA` `#909D2D` |
206
+
207
+ Both pass the lightness, chroma, colorblind (adjacent ΔE OKLab ≥ 8) and normal-vision (≥ 15) checks. The order is part of the validation. Typeface: Mozilla Text, falling back to `system-ui`.
208
+
209
+ ## Development
210
+
211
+ ```bash
212
+ npm test # tests (node:test)
213
+ npm run build # dist/plotagents.js for the browser
214
+ npm run examples # regenerates examples/svg and examples/index.html
215
+ npm run site # builds the GitHub Pages site into _site/ (docs, gallery, playground)
216
+ ```
217
+
218
+ MIT © Carlos Navarrete
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // CLI: plotagents spec.json [-o salida.svg|.html] [--lint] [--schema] [--tool [openai] [dashboard]]
3
+ // cat spec.json | plotagents > grafico.svg
4
+ // A spec with a `charts` list is a dashboard: it renders to a self-contained HTML page.
5
+ import { readFileSync, writeFileSync } from 'node:fs';
6
+ import { plot, toHTML, lint, schema, toolDefinition, describe, dashboard, lintDashboard, dashboardSchema } from '../src/index.js';
7
+
8
+ // `plotagents … | head` closes the pipe early: exit quietly instead of crashing.
9
+ for (const stream of [process.stdout, process.stderr]) {
10
+ stream.on('error', (e) => { if (e && e.code === 'EPIPE') process.exit(0); throw e; });
11
+ }
12
+
13
+ const args = process.argv.slice(2);
14
+ const flag = (f) => args.includes(f);
15
+ const opt = (f) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : undefined; };
16
+ const VALUE_FLAGS = new Set(['-o', '--out', '--tool']);
17
+ const TOOL_ARGS = new Set(['openai', 'anthropic', 'dashboard', 'chart']);
18
+ const input = args.find((a, i) => !a.startsWith('-') && !VALUE_FLAGS.has(args[i - 1]) && !(TOOL_ARGS.has(a) && args.slice(0, i).includes('--tool')));
19
+ const print = (s) => process.stdout.write(s.endsWith('\n') ? s : s + '\n');
20
+
21
+ if (flag('-h') || flag('--help')) {
22
+ print(`plotagents — gráficos bellos desde un spec JSON
23
+
24
+ Uso:
25
+ plotagents spec.json SVG a la salida estándar
26
+ plotagents spec.json -o grafico.svg guarda SVG
27
+ plotagents spec.json -o reporte.html página HTML interactiva (acepta un arreglo de specs)
28
+ plotagents tablero.json -o tablero.html dashboard (un spec con \`charts: [...]\`)
29
+ plotagents spec.json --lint revisa el spec y sugiere mejoras (JSON)
30
+ plotagents spec.json --describe descripción en texto del gráfico
31
+ plotagents --schema [dashboard] JSON Schema del spec (o del dashboard)
32
+ plotagents --tool [openai] [dashboard] definición de herramienta para agentes
33
+ cat spec.json | plotagents también lee de stdin`);
34
+ process.exit(0);
35
+ }
36
+ // Tool and schema flags accept "openai" and/or "dashboard" in any order after the flag.
37
+ const after = (f) => { const i = args.indexOf(f); return i >= 0 ? args.slice(i + 1).filter((a) => TOOL_ARGS.has(a)) : []; };
38
+ if (flag('--schema')) { print(JSON.stringify(after('--schema').includes('dashboard') ? dashboardSchema : schema, null, 2)); process.exit(0); }
39
+ if (flag('--tool')) {
40
+ const t = after('--tool');
41
+ print(JSON.stringify(toolDefinition({ flavor: t.includes('openai') ? 'openai' : 'anthropic', kind: t.includes('dashboard') ? 'dashboard' : 'chart' }), null, 2));
42
+ process.exit(0);
43
+ }
44
+
45
+ let raw;
46
+ try { raw = input ? readFileSync(input, 'utf8') : readFileSync(0, 'utf8'); } catch (e) { console.error('No pude leer el spec:', e.message); process.exit(2); }
47
+ let spec;
48
+ try { spec = JSON.parse(raw); } catch (e) { console.error('El spec no es JSON válido:', e.message); process.exit(2); }
49
+
50
+ const isDashboard = (s) => !!s && typeof s === 'object' && !Array.isArray(s) && Array.isArray(s.charts);
51
+
52
+ if (flag('--lint')) {
53
+ const list = Array.isArray(spec) ? spec : [spec];
54
+ const out = list.map((s) => (isDashboard(s) ? lintDashboard(s) : lint(s)));
55
+ print(JSON.stringify(Array.isArray(spec) ? out : out[0], null, 2));
56
+ process.exit(out.every((r) => r.ok) ? 0 : 1);
57
+ }
58
+ try {
59
+ const outFile = opt('-o') ?? opt('--out');
60
+ if (isDashboard(spec)) {
61
+ if (flag('--describe')) { print([spec.title, ...spec.charts.map((c) => { try { return describe({ data: spec.data, ...c }); } catch (e) { return e.message.split('\n')[0]; } })].filter(Boolean).join('\n')); process.exit(0); }
62
+ const html = dashboard(spec);
63
+ if (outFile) { writeFileSync(outFile, html); console.error(`✓ ${outFile}`); } else process.stdout.write(html);
64
+ } else {
65
+ if (flag('--describe')) { print((Array.isArray(spec) ? spec : [spec]).map(describe).join('\n')); process.exit(0); }
66
+ const html = (outFile && outFile.endsWith('.html')) || flag('--html') || Array.isArray(spec);
67
+ const result = html ? toHTML(spec, { title: (Array.isArray(spec) ? spec[0] : spec).title || 'plotagents' }) : plot(spec);
68
+ if (outFile) { writeFileSync(outFile, result); console.error(`✓ ${outFile}`); } else process.stdout.write(result);
69
+ }
70
+ } catch (e) {
71
+ console.error(e.message);
72
+ process.exit(1);
73
+ }