Aner Plot
Tell a clear scientific story with native 2D and 3D charts, scatter time frames from keyed CSV tables, offline country and city maps, optional packs and interactive notebooks.
Implementedimport aner.plot brings scientific charts, offline geographic maps, reusable themes and SVG export into the native Aner workflow. Compose immutable chart values with ordinary method chains, then display them beside the analysis they explain.
Use Aner 0.0.4 or newer and a matching VS Code extension for notebook display. A matching runtime remains necessary even when an extension is installed. See release and development status and the roadmap.
Native data profiles and named columns
The following adapters are development APIs and require the matching native development runtime and local editor support. Released runtime and Marketplace packages may predate them. They connect the immutable data population to the chart directly, without constructing intermediary Lists.
Every loaded table exposes a cached overview() report. Read its structured statistics directly or call report.summary() for combined structural and statistical text. Add with_profile when sampled quantiles and tracked categories are useful; those diagnostics add CPU and managed memory work while avoiding a separate traversal of retained rows.
import aner.data
import aner.plot
let source = data.scan_csv_auto("examples/fixtures/data_profiling.csv", "NA", 1048576, 0)
let table = source.with_profile(sample_rows: 1024, max_categories: 64)
.collect(max_rows: 0, max_bytes: 8388608, batch_rows: 256)
let report = table.overview()
print(report.summary())
plot.missingness(report).show()plot.distribution(report, column, bins) uses the retained numeric sample, and plot.categories(report, column) shows exact counts of tracked values with disclosed dictionary coverage. plot.scatter(table, x_column, y_column, max_points) preserves row pairing through an explicit ordered prefix, skipping pairs with a missing coordinate. It never pairs independently retained profile samples. Current physical units label the axes, and plot coordinates reject Int64 values outside [-2^53, 2^53] instead of rounding observation identifiers.
Charts own their bounded snapshot. Source recipe, digests, current and ancestral completeness, selected fields, units and sampling policy remain available through chart.provenance() and embedded export metadata, even after title, caption or theme changes. complete() describes traversal of the current source; origin_complete() also preserves incomplete preview ancestry. Saving an ordinary chart as .html embeds a static offline SVG; dashboard and spatial HTML retain their own local interactive renderers. Existing output files are preserved.
See data profiling for exactness, source coverage, sample/category and chart limits, and the climate analysis for attributed observations, scientific interpretation and native figures. These adapters do not add confidence intervals, causal inference, live data subscriptions or GPU profiling.
Charts from a source file
The updated VS Code Run File button keeps printed results in the task terminal and opens native Chart.show() output in an adjacent Aner Plots panel after a successful run. Charts work in both production and development mode; viewing a chart does not rerun the analysis. Notebook charts continue to belong to their producing cells.
A terminal prints text and cannot display SVG graphics directly. For a source run outside VS Code, explicitly route charts to a fresh local directory:
aner run examples/plot_story.aner --display-dir ./plot-resultsThe parent directory must already exist, and plot-results must not exist. Ordinary print output stays on stdout, accompanied by a short summary for each shown chart. The directory contains chart-0001.svg, subsequent numbered SVG files and manifest.json. Open the SVG files in a browser or compatible image viewer. Without --display-dir, the CLI retains its existing behavior of writing shown SVG markup to stdout.
This display channel stores rendered figures only; it does not serialize the program's retained arrays or other variables. It accepts at most 64 charts and 4 MiB of SVG per run. Successful runs publish a manifest with schema aner.display-files/1 and an outputs array of { "mime": "image/svg+xml", "file": "chart-0001.svg", "summary": "Chart(...)" } items. Summaries contain at most 512 UTF-8 bytes, and the manifest contains at most 256 KiB. Source errors preserve their normal diagnostics and remove owned, unpublished chart files. An externally terminated process may leave an unpublished directory; a manifest is the success marker. The editor removes its temporary chart files after reading them.
--display-dir is independent of --max-steps, --prod and --dev DIR; it does not change the execution budget or turn development inspection on. Use a separate fresh directory for a development report. The static SVG panel preserves native figures; the notebook renderer remains the route for interactive geographic, linked and 3D views.
A Boulder story: explain first, explore when useful
Start with a question and give the reader a useful initial view. This Boulder, Colorado example follows one invented week of bicycle counts at six illustrative locations, assigned the illustrative dates October 12 to 18, 2026. All counts are synthetic teaching values. The coordinates are illustrative, and the labels do not identify official monitoring stations. The example makes no claim about actual bicycle activity, unique riders, traffic safety or a particular calendar week.
Download the complete Boulder source or the notebook. The first two charts need no map pack. Only the geographic chart requires usa.co; it does not require the USA overview or any other state. Each chart uses a light theme, a question driven title, explicit units and a source caption. The figures below are native SVG outputs from that source.
The teaching data in JSON records the same daily counts and illustrative coordinates for independent checking. The source and notebook already contain these arrays; this download is optional and is not a runtime input dependency.
When does the pattern change?
All six daily series share one set of axes. The Creek and Campus crossing can be read directly, and each site can be selected without hiding the others. Campus has more counts on every weekday; Creek has more on Saturday and Sunday. This is a descriptive comparison of supplied observations. It is not a fitted trend or evidence for a cause. The source uses day numbers with their weekday meaning disclosed, since dedicated temporal and categorical axis formatters remain future work.
Which location has the largest weekly total?
The bar chart answers the ranking question without requiring a map or an interaction. Campus totals 4,340 counts over seven days, ahead of Creek at 3,960. Bars begin at zero, and the source supplies the weekly totals in descending order. These are event counts, not estimates of unique riders or population rates. All six sites appear on one common axis; separately constructed charts do not yet support explicit shared numeric limits.
Where are the differences?
The map adds geographic context to the same six sites. Marker area represents the weekly total already shown in the bars. Color represents the change from the weekday daily mean to the weekend daily mean, in percent:
100 * (mean(Saturday, Sunday) / mean(Monday, ..., Friday) - 1)Comparing daily means accounts for the two weekend days and five weekdays. Creek changes by +100%, Campus by −40%, and Chautauqua by +160% in this invented dataset. Positive change does not imply a larger weekly total. Read the numeric color legend and marker details; the continuous palette does not supply a special visual boundary at zero. The neutral polygon is context only, and carries no city aggregate. City boundaries are Census place geometry, not a street or cycle route map.
In a compatible Aner VS Code notebook, pan and zoom help inspect nearby locations and reveal labels as space becomes available. Marker values, color limits and relative areas remain fixed during navigation. Drag to pan, use +/−, and choose Reset to return to the initial view. The interactive map controls describe keyboard access, bounded navigation and static fallbacks. The exported figures above communicate the initial result without any interaction.
Try the linked Boulder explorer. This downloadable teaching demo starts from the same three native chart scenes and adds local date range and multi site controls. The map, period totals, daily trends and table update together. Save the HTML file and open it locally to explore without a connection, a running Aner session or installed map packs. Rerunning the source that constructs the boundary chart requires usa.co. The original demo is a prepared documentation artifact. The native dashboard recipe below creates a similar explorer from ordinary Aner source.
Filter dates and sites in the offline explorer
The prepared Boulder explorer includes an inclusive date range and a checklist for selecting several sites. October 12 to 18, 2026 is an invented teaching week, assigned to the same synthetic daily counts. These are illustrative dates, not newly acquired municipal observations.
Select a start and end date, then choose any combination of the six sites. Both endpoints count. The daily trend retains only observations in that range; bars and marker areas use each selected site's period total. The data table updates to the same dates and sites. Click a mark to focus one site, or Ctrl/Cmd/Shift click a visible mark to remove that site. Use the checkboxes to add sites again. Use Select all sites, Select no sites, or Reset filters to return to a clear state. Selecting no sites produces an explicit empty result.
Weekday and weekend means use only the days included in the range. Relative weekend change is 100 * (weekend mean / weekday mean - 1) only when both groups exist and the weekday mean is nonzero. A weekday only range, weekend only range or missing denominator displays N/A, with a neutral marker color, rather than a fabricated zero. For example, the complete weekend gives Creek 1,760 counts and Campus 840; its weekday comparison is unavailable. Friday through Saturday gives Campus 1,170 counts and a weekend daily change of −44%.
Drawing scales stay fixed so filtering cannot exaggerate a change. Daily axes retain the full teaching week and full data limits. Bars retain the original full week ordering and count axis. Marker area uses the full week maximum of 4,340 as its reference. The browser map uses a diverging color scale centered at zero; its fixed limits cover every valid contiguous date range, from −50% to +160%, rounded outward from the −44% and +160% data extrema, with a separate N/A swatch. These browser filter legends differ from the initial native SVG's sequential full week legend. Map pan, zoom and projection survive changes to the filters.
Invalid or reversed dates display an error and leave the last valid result visible. A valid date range outside the embedded week shows an explicit no observations result. The HTML embeds its teaching values, projected boundary geometry and all filtering code. Save it and open it locally: date and site filtering need no running Aner session, map installation or connection. Rerunning native boundary construction still requires only usa.co, and numerical plotting continues to load no map data.
The original explorer uses a prepared controller. Use plot.site_dashboard below for the corresponding date and site controls in notebooks and native HTML export. Individual charts with .link(group, ids) retain their single site emphasis behavior.
Link a site across views
Use .link(group: "boulder-sites", ids: ...) on each chart. A group joins views in the same notebook document; exact, case sensitive String IDs identify the observations. Supply one ID per line series, one per bar, or one per geographic point. IDs must be nonempty and unique within a chart. Group names permit 128 UTF-8 bytes and IDs permit 256 bytes each; control characters are rejected. Apply .link after all .add_line or .add_points calls. They follow the supplied order in that chart, so sorting bars requires sorting their IDs with them.
let trend = plot.line(days, creekDaily)
.add_line(days, campusDaily, name: "Campus")
.link(group: "boulder-sites", ids: List("Creek", "Campus"))
let totals = plot.bar(List("Campus", "Creek"), List(4340, 3960))
.link(group: "boulder-sites", ids: List("Campus", "Creek"))
trend.show()
totals.show()Click a line, bar or map point to emphasize its ID throughout the group. Each view also has site buttons for keyboard access. Select the same site again, choose Clear selection, or press Escape to clear. Selection preserves every observation, axis domain, point radius and color scale. IDs absent from another view have no matching mark there. Use a distinct group for an independent analysis.
The Boulder source gives all six daily series, ranked bars and geographic points the same IDs. Selection survives map pan and zoom. The selected point label receives priority when a collision free placement fits; site controls remain available if the point leaves the visible window. Dragging the map does not select a site.
The renderer shares selection locally; it does not run Aner again, fetch data or communicate with a kernel. Saved scenes retain their IDs and reopen with no selection. Clients without the compatible renderer and oversized scenes show the initial static SVG. .save(...) exports that initial figure, not the temporary selection state. Linking line and bar charts requires no map pack; replacing the boundary map with plot.geo_scatter keeps all three views independent of packs.
Design references and the next step
Darkhorse Visualization's Stronger Nation presents an explanation before deeper exploration and provides chart and data exports. The Care Board connects explanation and geographic exploration with access to methods, code and data. Alongside Opportunity Atlas, these are design references for clear scientific communication. Aner's charts here are original examples, without an affiliation with those projects.
The Boulder charts now share a linked site selection with a useful static starting point and visible data definitions. A selection follows an explicit site ID while preserving the complete data and fixed scales. The prepared browser explorer adds date range and multi site filters. The native daily site dashboard now supplies notebook date and multi site filters. General dashboard layouts and shared scale APIs remain future work. Prefer an interaction when it helps answer an additional question.
Create the explorer in a notebook or from plain Aner
Use plot.site_dashboard_table(table) to create a linked map, site totals, daily trends, availability heatmap and data table from a collected CSV snapshot. Inclusive date filters and multiple selected sites update all views locally. The same Aner analysis runs in .aner, .anernb and standard Jupyter .ipynb files.
Download the complete runnable source, the CSV, the VS Code .anernb notebook. Open the page generated directly by Aner, or the optional Colorado boundary variant. The CSV contains six illustrative Boulder sites on seven dates: all 42 counts are synthetic teaching data. The default dashboard needs no map pack.
import aner.data
import aner.plot
var schema = data.schema()
schema = data.column(schema, "date", "String", false)
schema = data.column(schema, "site", "String", false)
schema = data.column(schema, "longitude", "Float64", false)
schema = data.column(schema, "latitude", "Float64", false)
schema = data.column(schema, "count", "Float64", true)
let source = data.scan_csv("examples/fixtures/plot_boulder_sites.csv", schema, missing: "NA")
let bounded = data.bounded(source, max_scanned_rows: 11713,
max_read_bytes: 8388608, timeout_ms: 5000)
let table = data.collect(bounded, max_rows: 11712,
max_bytes: 4194304, batch_rows: 256)
let dashboard = plot.site_dashboard_table(table)
.title("Boulder: explore an invented teaching week")
.caption("Synthetic plot_boulder_sites.csv counts; illustrative positions, not monitoring stations.")
dashboard.show()
dashboard.save("boulder-dashboard.html")The CSV uses long format, one observation per site and date:
date,site,longitude,latitude,count
2026-10-12,Creek,-105.28,40.01,400
2026-10-12,Pearl,-105.277,40.018,450
2026-10-12,Campus,-105.264,40.006,650These first three records illustrate the format; use the complete download for all six sites and seven dates. The CSV header must match the schema's names and order. Date, site, longitude and latitude are required; true makes only the count column nullable. With missing: "NA", an unquoted NA count is missing. Empty fields are missing only if the scan explicitly uses missing: "". Declare longitude and latitude as Float64 in WGS84 degrees, not screen coordinates. The table recipe requires a complete materialized DataTable, meaning collection reached the end of input; individual observations may still be missing. An incomplete preview is rejected. It finds the five required columns by name, allowing any table column order and unrelated extra columns. Date and site must be Strings; longitude, latitude and count must be primitive Int64 or Float64 columns without units. The recipe does not open a DataScan, aggregate duplicate rows, sample or infer column types.
Dates are sorted and site order follows first appearance. Each site has one consistent finite WGS84 position and at most one row per date. An absent site/date row or nullable count becomes a missing observation, never zero. The adapter fills the daily calendar between the earliest and latest represented dates, including an interior day absent for every site. It cannot infer unrepresented leading/trailing dates or a site absent from the entire table. Duplicate site/date rows, missing date/site/position metadata, inconsistent positions and invalid nonmissing counts remain errors. Trend segments break at missing observations; a measured zero remains a valid point. Chart construction snapshots the validated table, so later CSV edits affect only a new read and construction.
Supply 1 to 32 unique site names containing 1 to 128 UTF-8 bytes without control characters, an inclusive calendar span of 1 to 366 valid ISO YYYY-MM-DD days, and finite nonmissing counts within 0 to 1e12. The maximum complete calendar has 11,712 site/day observations. The example bounds source reading to 8 MiB, five seconds and 11,713 records; the extra record permits an end of file check at the accepted row limit. Collection admits at most 11,712 rows in a 4 MiB managed memory budget, in batches of 256. A limit failure produces no partial data dashboard. These explicit budgets can reject otherwise valid larger input; change them deliberately. CSV validation retains the data module's contracts.
Missing observations, gaps and coverage
Open the missing data dashboard or its optional Colorado boundary variant, or download its CSV, .aner source, VS Code .anernb. The analysis code is identical in all three formats. It uses the nullable schema above with only this path change:
let source = data.scan_csv("examples/fixtures/plot_boulder_missing.csv", schema, missing: "NA")This synthetic fixture omits every Wednesday row and Creek's Tuesday row, explicitly marks Campus's Saturday and East's Friday through Sunday as NA, and records North's Sunday as a measured 0. Its 35 CSV rows expand to seven days and 42 expected observations, of which 31 are measured. Across the full week every site's period total is N/A; the separate observed subtotal is 13,780 with coverage 31/42.
| Selected observations | Period total | Observed subtotal | Coverage |
|---|---|---|---|
| All sites, October 12 | 2,220 | 2,220 | 6/6 |
| All sites, October 14 | N/A | N/A | 0/6 |
| East, October 17 to 18 | N/A | N/A | 0/2 |
| North, October 18 | 0 | 0 | 1/1 |
| Pearl, October 17 to 18 | 1,250 | 1,250 | 2/2 |
A period total is N/A if any expected observation is missing. Observed subtotal sums only measured counts and is itself N/A when none are measured; coverage always states how many observations are available. Weekday and weekend means require complete coverage within the included group. An absent group, missing count, zero weekday baseline or unrepresentable change gives N/A. This keeps a partial sum distinct from a complete total.
The map, bars, trends and table apply those rules together. A missing date leaves a line gap; it is never plotted at zero or connected across. An incomplete period total uses a neutral 5 px map marker and an N/A bar; measured zero has zero marker area and remains in the checklist and table. Axes, full data site order, marker reference size and the color domain remain fixed when filters change. Static SVG and interactive notebook/HTML outputs preserve the same missingness; the default needs no packs. An optional boundary map changes only geographic context.
Inspect coverage by site and date
The coverage heatmap, labeled Observation coverage, shows the full captured calendar: one row per site and one column per date. Its two states encode whether an observation exists, not the count's magnitude. A measured 0 is observed; an absent row or NA count is missing. Cell labels and tooltips report the site, ISO date, count or N/A, and observation state. The missing data example makes the all missing Wednesday visible alongside North's measured zero on Sunday.
The grid keeps every site and date visible as context while the current selection is highlighted. Changing the date inputs or site checklist updates that highlight and the map, bars, trends and summary table together. The grid's availability and snapshot coverage summary remain properties of the full snapshot; selected range coverage is reported separately in the status and summary table. A cell outside the active filter is not reclassified as missing. It never uses count magnitude as a coverage color scale.
Click a cell to select its site and focus the date range on that day. Ctrl/Cmd/Shift-click toggles that site's membership and still focuses the day; other selected sites remain selected. A row header button focuses its site while preserving the current date range; the same modifier keys toggle the site instead. Missing cells support the same selection controls. Clicking one Wednesday cell focuses one site and gives N/A with 0/1 coverage. Setting both date inputs to Wednesday while all six sites are selected gives N/A with 0/6 coverage. Selecting North's Sunday gives measured zero and 1/1 coverage.
Use the arrow keys and Home/End to move within the grid, and Enter or Space to activate the focused cell. Focus and selection have separate visible indicators. Large calendars scroll inside their own table, preserving access to the rest of the dashboard. These controls run in the same notebook renderer or exported HTML without a kernel request, CSV reread or map pack. Static SVG includes the initial availability grid and its observed/missing labels. Long calendars continue in stacked sections with repeated site/date headers and coverage for each section. Exact counts remain in cell titles when space is limited. SVG cells record the snapshot; the notebook renderer and HTML page provide interaction.
Brush dates and multiple sites
Drag across coverage cells with a mouse to select an inclusive rectangle of site rows and date columns. Release to apply those sites and the earliest/latest dates together to the map, bars, daily trends and summary table. Dragging in the opposite direction gives the same rectangle. Missing cells and measured zero cells are both selectable; brushing changes the filter, never the observations.
Ctrl/Cmd/Shift-drag adds the rectangle's site rows to the sites selected before the gesture and focuses the common date window on the brushed columns. This differs from a modifier click, which toggles one site. A preview shows the pending rectangle while the charts retain their last committed filters. Press Escape during the drag, or cancel the pointer gesture, to remove the preview and keep the previous selection. Hold the pointer near or beyond a scrolling table edge to reveal more dates or sites. Releasing outside ends at the nearest visible cell at the current scroll position. Cancellation preserves the filters; the table may remain scrolled.
In the missing data example, brush Pearl through North and October 13 to 16. That rectangle selects three sites and four dates: the period total is N/A, the observed subtotal is 4,480 and coverage is 9/12. Brush North and East on October 18 to see a measured zero beside a missing observation: the observed subtotal is 0 with coverage 1/2, while the period total remains N/A. The availability grid retains the rest of the snapshot as context.
Touch and pen keep their usual table scrolling and single cell tap selection. The existing date inputs, site checklist, row buttons and keyboard cell controls remain available as alternatives to dragging. Brush interactions run locally in .anernb, the Jupyter iframe and standalone HTML; they do not rerun Aner, reread the CSV or request map data. The static SVG preserves availability and its initial data summary without gesture controls.
The analysis call remains plot.site_dashboard_table(table), with .show() for notebooks and .save("fresh-dashboard.html") for an offline page. Use the updated native runtime and, for .anernb, its matching Aner extension; then export a fresh HTML filename to include brushing. Existing exported pages keep their bundled controls. Neither constructing a point only dashboard nor using its brush requires a map pack; optional boundary variants keep the same pack and offline viewing behavior.
Run from the project root containing examples/fixtures/plot_boulder_sites.csv: relative file paths use the process or kernel working directory, not the source or notebook folder. Downloaded notebooks need the CSV in the same relative folder tree, or the same path edit in all formats. The import, schema, read and dashboard code cells are byte identical in both notebooks and form the .aner source's analysis prefix. The source adds an export; notebook export is an optional new cell so Run All can reread the CSV without colliding with an existing HTML file.
For .anernb, open the file in VS Code with the matching Aner extension, select Aner — notebook, and Run All. Standard Jupyter uses the separate .ipynb file and optional Aner kernel; see the Jupyter setup. The extension uses a data only dashboard renderer. The Jupyter adapter supplies an HTML iframe with an opaque origin, scripts enabled only inside that sandbox and a policy forbidding network connections. Saved outputs follow the frontend's normal trust and script policy; review a notebook before trusting it. SVG is the fallback when scripts or the compatible renderer are unavailable.
From the project root, run aner run examples/plot_site_dashboard.aner in a writable directory. .save("boulder-dashboard.html") creates a standalone page; existing files are never overwritten. Open or share that file directly: the CSV is needed only while constructing the chart, and the exported page never fetches it. .html() returns the document as a String. .save("boulder-dashboard.svg") saves the full data static composite. Runtime exports use native Aner and bundled browser code: no external authoring tool, web server or CDN is required. Controls filter the captured data without contacting a kernel. Temporary filter choices and map navigation are not persisted into the native value or exported page. Rerun and save to a fresh filename to publish changed CSV data.
To add boundary context, construct a base map first and pass the same table with the named map argument:
let context = plot.map("usa.co.places", keys: List(), values: List())
.extent(west: -105.34, south: 39.96, east: -105.20, north: 40.09)
.projection("lambert_azimuthal_equal_area")
let withBoundaries = plot.site_dashboard_table(table, map: context)
.caption("Synthetic CSV counts; generalized Census 2025 municipal boundaries, no streets.")
withBoundaries.show()Only this optional construction requires usa.co. The map must be a geographic boundary chart without existing point layers; the recipe adds the table's positions. Set extent and projection on that map first. Its geometry and the dashboard caption travel inside the exported HTML and notebook scene. Include the data source in that caption, as the notebook does. Recipients can view those outputs offline without the CSV or pack; rerunning construction needs the CSV and, for this variant, the pack again. Importing aner.plot, collecting CSV data, numerical plotting and the point only dashboard load no boundary data.
plot.site_dashboard(dates, sites, positions, counts) remains available when you already have Lists. counts is one numeric List per site, with one value per strictly increasing date; positions are GeoPosition values. It uses the same dashboard, site/count bounds, notebook display and export behavior. This older List API retains its explicit date sequence and complete numeric count rows; use the table recipe for nullable counts and daily calendar expansion. For example:
import aner.geo
let dates = List("2026-10-12", "2026-10-17")
let sites = List("Creek")
let positions = List(geo.position(longitude: -105.280, latitude: 40.010))
let counts = List(List(400, 840))
plot.site_dashboard(dates, sites, positions, counts).show()The dashboard keeps numeric axes, full data bar order, marker reference size and a diverging color domain fixed across filters. Color compares included weekend and weekday daily means only when both groups are complete and the weekday baseline is positive; otherwise it is N/A. Table based dashboards use the nullable aner.site-dashboard/2 scene; compatible readers also accept older complete /1 scenes. Map navigation survives filtering. Invalid dates retain the last valid result; no sites or no included dates produce an explicit empty state. Multiple dashboards have independent controls. Payloads are bounded: oversized interactive scenes retain SVG in notebooks, while an explicit HTML export reports the limit. This API is a recipe for daily site counts; general layouts, arbitrary widgets and server callbacks remain future work.
3D charts and a fourth variable
Aner 0.0.4 or newer supplies plot.scatter3d(x, y, z), plot.line3d(x, y, z) and plot.surface3d(x, y, z). The first two take equal length finite numeric vectors in supplied order. They neither sort nor fit observations. A fourth values vector in scatter3d(x, y, z, values) adds an independent scalar color channel. Use the matching notebook integration for local rotation and zoom; a native SVG supplies the initial view.
Explore the synthetic Boulder 3D example, or download the .aner source, VS Code .anernb. All six files in the two example families contain the same analysis in their corresponding formats. Aner creates the complete experience from this program: .show() supplies notebook interaction, and .save("boulder-3d.html") directly writes the standalone HTML with captured data and its bundled renderer. The .aner source appends fresh HTML and SVG exports to the same chart building analysis used by both notebooks. The Boulder demonstration has six frames of 63 invented samples in local Cartesian metres and a separate invented temperature; it is not real terrain, WGS84 coordinates or municipal sensor data. It requires the local CSV while constructing the chart and no map pack. The trajectory and surface examples need no input file.
The image below previews the source authored third capture (zero based frame 2), with XYZ rotation 15°, −10°, 20° and zoom 1.2. Open the interactive 3D plot, then drag inside it with the mouse or use Rotate plot X/Y/Z controls. No kernel, CSV or map packs are needed to rotate the exported page.
import aner.plot
let chart = plot.scatter3d(
x: List(0.0, 120.0, 240.0),
y: List(0.0, 120.0, 0.0),
z: List(45.0, 65.0, 52.0),
values: List(18.0, 20.0, 16.0))
.labels("Local east (m)", "Local north (m)", "Height (m)")
.color_label("Temperature (°C)").color_limits(12.0, 24.0)
.aspect("equal").view(azimuth: -45.0, elevation: 28.0)
.title("Three invented samples; color is a fourth variable")
chart.show()
chart.save("new-spatial-chart.html")
chart.save("new-spatial-chart.svg")Time slider and playback in the Boulder 3D example
The Boulder source, .anernb use plot.scatter3d_frames_table(table) after a typed, bounded read of the same local CSV. The offline time explorer contains six supplied frames of 63 stable observation indices, or 378 total records, matching the earlier matrix based scene. XYZ stays fixed in this teaching fixture, while invented temperature warms and cools by offsets −1, 0, 1, 2, 1 and 0 °C. The values are stored in the CSV; the analysis does not generate coordinates, Lists or temperatures. Coordinate domains span the complete capture set, and every frame uses the same fixed 12 to 24 °C color domain. The shared source explicitly calls .rotation(x: 15.0, y: -10.0, z: 20.0).view_zoom(zoom: 1.2).time_frame(frame: 2), so the notebook output, native SVG and exported HTML all start at the authored third capture.
Load captures from CSV
import aner.data
import aner.plot
var schema = data.schema()
schema = data.column(schema, "time", "String", false)
schema = data.column(schema, "site", "String", false)
schema = data.column(schema, "x", "Float64", false)
schema = data.column(schema, "y", "Float64", false)
schema = data.column(schema, "z", "Float64", false)
schema = data.column(schema, "value", "Float64", false)
let source = data.scan_csv("examples/fixtures/plot_boulder_3d_frames.csv", schema, missing: "NA")
let bounded = data.bounded(source, max_scanned_rows: 10001,
max_read_bytes: 1048576, timeout_ms: 5000)
let table = data.collect(bounded, max_rows: 10000,
max_bytes: 1048576, batch_rows: 64)
let captures = plot.scatter3d_frames_table(table)
.labels("Local east (m)", "Local north (m)", "Height (m)")
.color_label("Temperature (°C)").color_limits(12.0, 24.0)
captures.show()The long format CSV header is time,site,x,y,z,value, with one row per explicit time label and stable site ID. All six fields are required in every actual row; this example declares nonnullable String time/site and Float64 coordinates/value. The table adapter finds required columns by name, accepts any table column order and ignores unrelated extra columns. The CSV header must still match its declared scan schema, including order. Numeric columns must be primitive Int64 or Float64 without unit descriptors. Float64 values must be finite; Int64 values must lie within −9,007,199,254,740,992…9,007,199,254,740,992 (±2^53), including the endpoints. Larger Int64 magnitudes reject even if that individual integer has an exact Float64 representation. A nullable schema is accepted only when every required cell is present.
Time and site IDs must be nonempty XML compatible UTF-8 text of at most 128 bytes without C0 or DEL controls. Both domains retain global first appearance order; the adapter does not parse or sort timestamp labels. Every time/site combination must occur exactly once, with the same complete site set in every frame. Duplicate pairs, absent pairs and null cells reject rather than becoming zeros or inferred observations. First seen site order defines stable observation indices, and keyed site matching aligns later rows even when coordinates move. Site IDs align records but are not displayed by the current spatial inspector.
The fixture establishes B001: B063 in its first frame and deliberately rotates or reverses row order in every later frame. Identity alignment preserves the same 63 observations and six captures despite CSV row order. Supply a complete materialized DataTable with 1 to 10,000 rows, 1 to 120 time labels and at most 10,000 time/site pairs; an incomplete preview is rejected. The frame/site product is checked before allocating the dense frame snapshot. Collection here is bounded by 10,000 selected rows, 10,001 scanned rows to permit an end of file check, 1 MiB read and managed collection budgets, five seconds and batches of 64. A budget failure creates no partial chart; these limits may deliberately reject larger input.
Run from the project root containing examples/fixtures/plot_boulder_3d_frames.csv. Relative CSV paths use the process or kernel working directory, not the source or notebook directory. Downloaded notebooks need the same relative folder tree, or a consistent path edit in all formats. The three analysis cells are byte identical in both notebooks and form the .aner source's analysis prefix. Run All writes no files; add an export cell with fresh paths when needed. Source execution appends HTML and SVG saves in the working directory, where existing paths are never replaced.
Chart construction copies the complete validated table into an immutable snapshot. Changing or removing the CSV afterward does not affect a retained Chart, its HTML or its SVG. Rerun the read and construction to adopt CSV edits, then export a fresh filename. The standalone HTML includes all captures and controls, so recipients need neither the CSV, map packs nor a running kernel to view it offline. The CSV is local construction input, not a browser request.
Use explicit matrices
plot.scatter3d_frames(times, x, y, z, values) remains available when frame major numeric matrices are already in memory:
import aner.plot
let captures = plot.scatter3d_frames(
times: List("Morning", "Afternoon"),
x: List(List(0.0, 120.0), List(0.0, 120.0)),
y: List(List(0.0, 120.0), List(0.0, 120.0)),
z: List(List(45.0, 65.0), List(45.0, 65.0)),
values: List(List(16.0, 18.0), List(19.0, 21.0)))
.labels("Local east (m)", "Local north (m)", "Height (m)")
.color_label("Temperature (°C)").color_limits(12.0, 24.0)
captures.show()
captures.save("new-time-explorer.html")All four numeric inputs are frame major matrices with one row per label and one column per observation index. Supply 1 to 120 frames with an equal, nonempty point count in every row and at most 10,000 total frame/point records. Each coordinate and scalar must be finite. A rank two numeric Tensor or NDArray can supply an explicit frame by point matrix; nested Lists supply the same row order. No frame broadcasting, irregular row shapes, missing value filling or coordinate based record matching is inferred. Index i must identify the same caller defined observation across frames, even if its XYZ coordinates move.
times contains unique nonempty, XML compatible UTF-8 String labels of at most 128 bytes, without C0 or DEL control characters. Labels retain their supplied order; the constructor does not parse dates, sort timestamps, infer a timezone or calculate time intervals. The Boulder labels explicitly use assigned UTC text for an illustrative 9am: 7pm MDT teaching day. None represents a real observed capture.
The viewer opens paused at its source authored frame: capture 3/6 in the Boulder example, selected by zero based .time_frame(frame: 2). Without an authored frame override, a framed chart starts at its first capture. Use the labeled slider or previous/next controls to inspect a capture, or Play/Pause to advance through the sequence. Playback steps once per second and stops at the final frame. It does not replay elapsed hours from timestamp text, interpolate intermediate data or start automatically. Scrubbing, editing frame controls, inspecting an observation or changing the camera pauses playback; losing window focus or hiding its tab also pauses it. Slider changes update the geometry, scalar colors, frame label, inspector and paged table together. The camera, selected observation index, full capture coordinate domains and scalar limits stay fixed as frames change.
Native SVG exports the source selected frame and authored camera, XYZ rotation and zoom, with the capture label and shared full capture scales. The Boulder SVG therefore shows capture 3/6. Notebook and native standalone HTML retain the complete bounded frame snapshot and open paused at the source authored frame. Temporary slider, playback and camera state do not mutate the native Chart or change a later source export. To publish a different reproducible capture set or ordering, change the inputs and rerun the same analysis. All controls run locally in .anernb, Jupyter and offline HTML; no kernel callback, new position datatype, map pack or network connection is needed.
Surface topology, units and camera
surface3d(x, y, z) takes two strictly increasing axis vectors of at least two values each. Supply exactly y.size * x.size finite z values in row major order: z[row * x.size + column]. A rank two Tensor or NDArray for z must have that exact shape; a flat numeric vector can explicitly supply the same order. Each neighboring grid cell is split into two flat triangles. Each triangle uses the average of its three vertex color ratios; exact vertex values remain in the data table. There is no inferred mesh for irregular observations, fitted surface, missing value imputation or unsupplied volume. Missing/nonfinite inputs are rejected. Surface color represents z; the initial implementation accepts an independent fourth scalar only for scatter charts.
The trajectory and surface source, .anernb demonstrate a supplied helix and an analytically sampled saddle. Open the trajectory or the surface. The latter has 17 y rows, 21 x columns and 357 vertices. Color repeats response height; it is not an independent fourth variable.
| Modifier | Contract |
|---|---|
.labels(x, y, z) | Three String axis labels; disclose units and coordinate conventions |
.view(azimuth, elevation) | Reproducible initial orthographic camera in degrees; azimuth −180…180, elevation −90…90 |
.rotation(x, y, z) | Source authored 3D XYZ angles, each finite and within −180…180 degrees; fixed X then Y then Z order |
.view_zoom(zoom) | Source authored 3D zoom, finite and within 0.5…3 |
.time_frame(frame) | Source authored zero based captured frame index; framed scatter only, and the index must exist |
.aspect("auto") | Default; normalize each coordinate axis independently, so screen slopes and lengths are not physical ratios |
.aspect("equal") | One numeric unit has the same display length on all axes; appropriate only after using compatible coordinate units |
.color_label(text) | Name the scalar and its units on a colored scatter or surface legend |
.color_limits(minimum, maximum) | Explicit finite increasing limits on a colored scatter or surface; values outside are clamped in color while exact values remain in inspection |
The display uses an orthographic projection, so camera distance does not change point size. Local rotation and zoom preserve every supplied observation, coordinate domain and color limit. The XY, XZ and YZ presets and data table support checking overlap and exact coordinates. Axis colors and labels do not infer a coordinate reference system. GeoPosition remains the checked WGS84 longitude/latitude type for maps; generic Cartesian XYZ uses existing numeric vectors and needs no new position datatype. Convert geographic or physical units explicitly before applying equal aspect; a spherical map display projection is not a Cartesian analysis CRS.
Rotating a plot can reveal structure, but marks can still hide each other and projected distances depend on the view. Surface triangles use bounded painter ordering; overlapping triangles need not have exact solid geometry occlusion. For precise comparisons, use orthogonal views, 2D scatter/line charts, heatmaps or small multiples alongside the 3D display. The renderer does not apply lighting that could obscure the meaning of scalar colors.
What does plotting 4D mean?
A fourth dimension needs an explicit visual encoding. The initial API supports three coordinates plus one scalar in color, rather than pretending that a fourth independent spatial axis fits directly on a screen.
| Meaning of the fourth variable | Useful representation | Current support and tradeoff |
|---|---|---|
| A measured scalar at XYZ observations | scatter3d(x, y, z, values) plus a labeled color legend | Implemented offline. Fixed limits make colors comparable; occlusion and color precision remain limitations |
| Ordered time for the same observations | scatter3d_frames(...) or scatter3d_frames_table(table) with a slider and Play/Pause | Implemented offline. Explicit matrices or a complete keyed table, stable record indices, shared coordinate/color domains and a paused source selected frame; uniform one second steps without interpolation |
| A fourth parameter in an experiment | Named slices or small multiples at explicit parameter values | Use explicit filtered charts now; a general slice controller is future work. Disclose interval boundaries and avoid silently interpolating between observations |
| A field throughout XYZ, potentially through time | Explicit volume/slice or isosurface methods | Not implemented. Requires grid semantics, missingness, interpolation and opacity contracts; a surface alone does not represent a volume |
| Several variables with no meaningful spatial geometry | Pairwise 2D plots, heatmaps, parallel coordinates or dimensionality reduction | Existing 2D charts can provide explicit comparisons. A native pair-plot/parallel-coordinate or reduction pipeline remains future work; report transformations rather than implying extra physical axes |
Color works best here when the extra scalar is read with its legend and checked in the table. .color_limits(...) keeps the same meaning across deliberately comparable charts. Zero and negative scalar values are valid. A constant automatic color domain uses the palette midpoint; it does not invent variation. Camera changes never rescale colors. Discrete supplied scatter frames now have local time controls. Arbitrary 4D spatial rotation, linked brushing with dashboard sites, interpolated animation and volume rendering remain outside this contract.
Create the experience with Aner and save a chosen view
The complete downloadable .aner program creates the native Chart, shows it, and writes boulder-3d.html directly. Both notebook formats contain the same chart building cells and call .show() to obtain the same local controls. No website page or external chart builder is needed to generate that HTML. Run All in the supplied notebooks writes no files; add an export cell with fresh paths when you want a standalone copy.
For a reproducible published orientation, author it in Aner. The Boulder program already uses this view, so its SVG and HTML agree with the notebook's initial display:
let published = boulder
.view(azimuth: -45.0, elevation: 28.0)
.rotation(x: 15.0, y: -10.0, z: 20.0)
.view_zoom(zoom: 1.2)
.time_frame(frame: 2)
published.show()
published.save("fresh-boulder-view.svg")
published.save("fresh-boulder-view.html")Every modifier returns an immutable Chart copy. Angles must be finite and within −180…180 degrees; zoom must be finite and within 0.5…3. .time_frame accepts only a valid zero based index on a captured frame chart: index 2 means UI frame 3. Existing .view keeps its azimuth −180…180 and elevation −90…90 bounds. These source settings govern native .show(), .svg(), .html() and fresh .save(...) output. Existing files are never overwritten.
After rotating or choosing another capture in the viewer, use Download PNG, Download SVG or Save interactive HTML to retain that live view. Export pauses playback. PNG contains the complete labeled figure, rasterized proportionally to at most two million pixels with each dimension at most 4,096 pixels; the export status reports its actual width and height. SVG retains vector marks, title, caption, axes, color legend, the current capture/view labels and exact current frame observations in metadata. These figure exports contain the chart rather than its control widgets or paged inspection table. Native Chart.save still writes SVG or supported HTML; the PNG encoder is supplied by the local browser viewer.
Save interactive HTML embeds every captured frame, the local renderer and a separate validated aner.spatial-state/1 view record. Reopening restores the saved camera, XYZ angles, zoom, frame, selected observation and table page, always paused. The captured scene and original authored Reset target stay intact: Reset/Home restore authored camera/XYZ/zoom and retain the currently selected frame and inspection state. The HTML works offline without the CSV, a kernel, Aner installation or map packs. Notebook and browser policies can restrict downloads; SVG and an exported standalone HTML page provide the documented alternatives when local PNG rendering is blocked.
Expand Recreate this view in Aner to select and copy the generated camera/XYZ/zoom/frame method chain into your own program. Replace the placeholder chart with your variable, such as boulder, assign the returned Chart to a new binding, and save to fresh paths when those choices should become part of a repeatable analysis. Viewer downloads and this generated code do not write into kernel variables or edit the source file; running the copied code explicitly creates a new authored Chart. Observation selection and table paging remain local inspection state.
One analysis in notebooks and offline HTML
The compatible .anernb renderer and Jupyter adapter use immutable aner.spatial-view/1 snapshots for static charts and aner.spatial-view/2 snapshots for framed scatter charts, matching chart.html() and chart.save("fresh.html"). Standalone HTML embeds its data and local renderer and needs no kernel, native executable, network or installed map pack to view. Execution still needs the matching updated native runtime and integration. Jupyter HTML is isolated in an opaque origin iframe with local scripts, blob image rendering and user triggered downloads enabled, while external connections remain disabled; saved outputs follow frontend trust policies. Frontends that suppress interactive output retain the native SVG fallback.
Drag inside the plot with the mouse to orbit its camera. For direct axis turns, use the Rotate plot X, Y and Z degree fields (−180…180, step 1) or the adjacent ±15° buttons. The existing azimuth/elevation controls change camera orbit separately. Use local zoom to magnify, orthogonal presets to inspect projections, and Reset to recover the authored initial view. Reset and Home restore the source authored camera, XYZ angles and zoom while keeping the current frame, selected observation and table page. XY/XZ/YZ presets clear XYZ offsets to preserve truthful plane views. Without authored overrides, XYZ angles start at zero and zoom at one. Keyboard controls and the paged data table provide an alternative to dragging. Touch scrolling remains available. Static spatial SVG stores the exact displayed observations in its metadata. Framed charts export the labeled source selected frame using shared full capture scales; the HTML table presents the current frame directly. These are temporary display choices; .save(...) exports the source defined initial view, not the current browser camera. Use .view(...), .rotation(...), .view_zoom(...) and .time_frame(...) in code, then rerun for a reproducible published view. Source examples contain no saved execution history.
Axis rotations are right handed about the scale normalized full data plot center, applied in fixed X then Y then Z order before the camera. They are view controls, not a coordinate transformation saved into the analysis. Under auto aspect, each axis has already been normalized independently, so this is not a physical rotation in original units. Mouse orbit and camera edits retain axis offsets; changing a frame preserves them, the camera and selected observation. Manual rotation pauses playback. Raw coordinates, values, shared domains, CSV input and native Chart stay unchanged, and later source exports still use their authored initial view. These controls run offline in notebooks and standalone HTML; static previews and SVG files do not rotate.
Static spatial charts allow 1 to 10,000 points; framed scatter charts allow 1 to 120 frames and at most 10,000 total frame/point records; surfaces require at least 2×2 vertices and at most 10,000 in total. All coordinates and color inputs must be finite. Numeric collection adapters retain the ordinary plot contracts, and construction copies values into an immutable snapshot. Existing scene and notebook budgets still apply: an interactive scene that cannot fit retains the initial SVG when that SVG itself fits the 4 MiB cell budget. A larger static notebook output reports the cell limit; use a local SVG export or reduce the data. An explicit HTML export reports an interactive scene limit instead of silently dropping controls. The interactive canvas uses a bounded raster preview with at most two million backing pixels (about 8 MiB for its RGBA buffer), even for a larger requested chart size; projection coordinates and source data remain unchanged. Native SVG remains a full vector export. The 3D renderer adds no map data, map pack, external plotting dependency, tile service or CDN.
Import and memory use
import aner.plot enables plotting names and types. It does not open map packs or parse boundary geometry. Line, scatter, bar, histogram, box, heatmap and standalone plot.geo_scatter charts do not request geographic assets. Custom plot.choropleth uses only the GeoJSON supplied by the caller.
plot.map, plot.world, plot.usa and plot.boundaries materialize only the selected catalogue entry. Map construction releases temporary GeoJSON text after parsing; the immutable chart owns its geometry until its last reference is released. Focus, extent, projection and styling share the source geometry and do not load boundaries again. plot.boundaries returns an owned String, whose lifetime follows ordinary values. There is no process lifetime raw map String cache; constructing a new map parses its selected asset again.
country.jpn loads one national outline; chile.region.rm loads one Chilean administrative feature. Neither requires a world or country overview. Choosing chile and then focusing CL-RM keeps all 16 regions of that selected country chart.
Boundary GeoJSON is distributed in optional offline map packs instead of the executable. The runtime retains only catalogue metadata and accepts exactly the boundary revisions it was built against. Install only the countries or states your analysis needs; numerical plotting and aner.geo require no map packs. A separate map import is unnecessary. Operating system paging and allocator reuse determine resident memory, so freeing a chart does not guarantee an immediate drop in process RSS.
Load one state, province or region
Use the worldwide single region catalogue to select from 4,838 independently optional subdivision/source-unit packs. The index checks every one of the 249 geographic units and records source hierarchy, vintage, code scheme and genuine coverage gaps. It does not relabel an undivided country as a region.
import aner.plot
plot.map("region.chl.rm", keys: List("CL-RM"), values: List(16.0))
.projection("lambert_azimuthal_equal_area")
.title("One selected Chilean region").show()Install only region.chl.rm.anermap to run that chart; it does not load Chile's country outline or any other Chilean region. For a Boulder point over just Colorado use region.usa.co / US-CO, as shown in the source and notebook examples. The older usa.co county/place pack remains separately optional for a Boulder municipal boundary. Full offline source attribution and licenses stay with the selected pack and output.
Install only the maps you need
These commands require a compatible native runtime with map pack support. The runtime package contains no boundary GeoJSON. Map packs are separate, platform independent .anermap files. Copy the required files onto the target computer, then install them locally:
aner maps list
aner maps path
aner maps install /media/maps/region.chl.rm.anermap
aner maps install /media/maps/chile.region.rm.anermap
aner maps install /media/maps/country.jpn.anermap
aner maps install /media/maps/chile.anermap
aner maps install /media/maps/mexico.anermap
aner maps install /media/maps/canada.anermap
aner maps install /media/maps/usa.co.anermap
aner maps install /media/maps/usa.ca.anermapReplace /media/maps with the local folder holding your pack files. Each .anermap carries its source provenance and notices. Installation, listing and rendering make no network requests. The installed native runtime handles these operations directly. A missing pack error names the pack required by the selected catalogue. aner maps list shows available pack IDs and installation status. aner maps remove usa.co removes the current runtime's installed Colorado revision.
| Optional pack | Catalogues it supplies |
|---|---|
region.<country>.<key> | One independent subdivision or explicitly described source unit; exact ID and join key from the subdivision index |
country.<code> | One national outline, e.g. country.fra, country.jpn or country.chl; independent of world |
source.<code> | One separately identified non ISO source map unit; see the country index |
chile.region.<suffix> | One Chilean region, e.g. chile.region.rm; independent of chile |
world | world, used by plot.world |
usa | usa, used by plot.usa; overview of 50 states and DC |
chile, argentina, europe, mexico, canada | Corresponding regional catalogue |
south.america | South America country overview |
bolivia, brazil, colombia, ecuador, guyana, paraguay, peru, suriname, uruguay, venezuela | Corresponding administrative region catalogue |
usa.<postal> | Both usa.<postal>.counties and usa.<postal>.places |
There are 5,192 optional packs supplying 5,243 selectable layers, including 249 ISO coded country/territory outlines, 20 additional source map units and 16 independent Chilean regions, alongside the existing overview, administrative and U.S. state packs. Install usa.co for Boulder, usa.ca for San Francisco, Los Angeles and Palo Alto, and usa.ny, usa.hi or usa.tx for New York, Hawaii or Texas. State packs work independently of the usa overview. usa does not install all state detail. The complete chart story needs world, usa, chile, argentina, europe, usa.co and usa.ca; the city examples additionally need usa.ny, usa.hi and usa.tx. The Mexico/Canada examples need mexico and canada.
The plot collection contains those 23 packs: world, usa, chile, argentina, europe, mexico, canada, usa.co, usa.ca, usa.ny, usa.tx, usa.hi, south.america, bolivia, brazil, colombia, ecuador, guyana, paraguay, peru, suriname, uruguay and venezuela. Keep the individual .anermap files separate from the runtime, and install only those needed by your analysis. The Boulder story above uses only usa.co.
Obtain only the selected .anermap files from your research distributor, then transfer them to the offline computer and install them with the matching runtime. A collection groups independent packs for distribution; installing one file does not install the others.
The native installer checks pack identity, exact revision, lengths and SHA-256 hashes against the runtime's pinned catalogue before activation. Installed revisions coexist beneath the map root, so a runtime update cannot silently replace the geometry used by an older runtime. These hashes check pinned content; they are not a publisher signature. Keep those notices when sharing installed map data; archive files already carry them.
aner maps path prints the map root. An absolute ANER_MAPS_DIR overrides it; otherwise ANER_HOME/maps applies when ANER_HOME is set. Defaults are ~/Library/Application Support/Aner/maps on macOS, $XDG_DATA_HOME/aner/maps on Linux (normally ~/.local/share/aner/maps), and %LOCALAPPDATA%\Aner\maps on Windows. Set the same environment for terminal and notebook processes when using a custom root. For an offline project or deployment, transfer the matching runtime, required .anermap files and your input data together. A standalone exported SVG can be viewed without installing its source pack.
Start with the complete example
Download the Aner source or the VS Code notebook. With a compatible installed aner command, check and run the source:
aner check plot_story.aner
aner run plot_story.anerThe source emits sixteen charts: a comparison line, scatter, bar, histogram, box, heatmap, a custom geographic join, world and USA maps, plus Chile, Argentina, Europe and county/place examples for Colorado and California. Install the seven story packs listed above before running the full source; the plot collection also supplies all city and Mexico/Canada examples. It needs no connection or credentials; all measurement values are included. All values are synthetic teaching data. Command line execution emits the chart display data; use the notebook to view each chart beside its producing cell, or call .save("fresh-chart.svg") to export one.
Open the notebook in VS Code, select the compatible Aner runtime, restart the notebook session and choose Run All. The notebook also shows a dark version of the same comparison chart. Its setup cell stores values without drawing a chart. Subsequent chart expressions and .show() calls produce outputs below their own cells, including two separate outputs in the distribution cell.
API reference
Chart constructors return a Chart; the plot.geojson and plot.boundaries loaders return GeoJSON String text. Supply finite numeric List, Array, DynamicArray, NDArray or Tensor inputs. Series accept vectors; heatmaps accept a flat sequence with explicit dimensions or a matching matrix. Numeric lists may mix Int64 and Float64. Strings, Booleans, nulls and nonfinite values are rejected as numeric observations. Integers outside the exact Float64 range from negative 2^53 through positive 2^53 are rejected.
| Constructor | Input and meaning |
|---|---|
plot.line(x: Any, y: Any) | Equal length coordinates, connected in supplied order |
plot.scatter(x: Any, y: Any) | Equal length coordinates, one point per observation |
plot.geo_scatter(positions: List, values: Any[, labels: List]) | WGS84 GeoPosition observations colored by supplied numeric value; no pack needed |
plot.bar(labels: List, values: Any) | String categories and their supplied numeric values |
plot.histogram(values: Any, bins: Int64) | Counts in equal width bins; omitted bins defaults to 10 |
plot.box(values: Any) | Observed median, quartiles, whiskers and outliers |
plot.heatmap(values: Any, rows: Int64, columns: Int64) | Numeric cells in row major order, matching the declared shape |
plot.choropleth(geojson: String, property: String, keys: List, values: Any) | Explicit String key join to supplied GeoJSON regions |
plot.world(keys: List, values: Any) | Offline world regions joined by Natural Earth ADM0_A3 |
plot.usa(keys: List, values: Any) | Offline states and DC joined by uppercase postal code |
plot.geojson(path: String) | Read bounded local GeoJSON text for a custom choropleth |
plot.map(region: String, keys: List, values: Any) | Select an installed catalogue and join its declared String key |
plot.boundaries(region: String) | Return the selected catalogue as GeoJSON String text |
import aner.plot
let weeks = List(1.0, 2.0, 3.0, 4.0)
let response = List(12.0, 15.0, 14.0, 19.0)
let trend = plot.line(x: weeks, y: response)
.title("Response increased in this synthetic example")
.labels(x: "Week", y: "Response (arbitrary units)")
.caption("Synthetic measurements; four observations, no causal claim.")
.annotate(x: 4.0, y: 19.0, text: "Last observation")
trend.show()Construction snapshots the inputs. Later collection mutations do not change an existing chart. Sort time coordinates deliberately: a line follows the given order. Bars do not aggregate a table, and histograms report counts rather than probability density. Explicitly collect and filter the desired data before constructing a chart.
Axes and color scales disclose shared numeric offsets or powers of ten when close values have large magnitudes. Tooltips retain the full actual values so compact labels do not hide the supplied measurements.
Box quartiles use linear interpolation at sorted position (n - 1) * p. Whiskers reach observed values within 1.5 interquartile ranges; points beyond them are drawn individually. Whiskers describe sample spread, not confidence intervals. Histogram bins include their left boundary and exclude their right boundary, except the final bin includes the maximum.
Compose a clear scientific story
Every modifier returns another chart. Retain the result with an assignment or chain. There is no implicit current figure and no global plotting theme.
| Method | Result |
|---|---|
.title(text: String) | Set a supported takeaway |
.labels(x: String, y: String) | Name variables and units |
.caption(text: String) | Record source, population, exclusions and uncertainty definition |
.extent(west: Float64, south: Float64, east: Float64, north: Float64) / .extent(bounds: GeoExtent) | Set a geographic viewport |
.focus(key: String, padding: Float64 = 0.15) | Fit a boundary feature, keeping nearby geography |
.projection(name: String) | Select a spherical geographic display projection |
.annotate(x: Float64, y: Float64, text: String) | Mark a supplied data coordinate |
.add_line(x: Any, y: Any, name: String) | Add a named line to a line or scatter chart |
.add_points(positions: List, values: Any[, labels: List]) | Add value colored GeoPosition observations to a geographic chart |
.point_sizes(values: Any[, max_radius: Float64]) | Scale geographic marker areas by nonnegative values; default maximum radius is 14 pixels |
.point_size(radius: Float64) | Use one geographic marker radius, clearing a value to size mapping |
.point_labels(mode: String) | Choose geographic point label placement: "avoid" (default), "all", or "none" |
.link(group: String, ids: List) | Link geographic points, bars or line series by exact stable IDs in a local notebook group |
.theme(theme: ChartTheme) | Attach an immutable presentation snapshot |
.size(width: Int64, height: Int64) | Choose bounded SVG dimensions |
.show() | Emit one chart output for the current execution |
.svg() | Return the SVG as String |
.summary() | Return a plain text chart description |
.save(path: String) | Write SVG or supported standalone HTML to a fresh path; existing files are not replaced |
Company theme and named comparison
let corporate = plot.theme("light").company(
name: "Example Research",
background: "#FFFFFF",
foreground: "#17233B",
colors: List("#007C91", "#C6601D", "#6950A1")
)
let comparison = trend
.add_line(weeks, List(10.0, 12.0, 13.0, 14.0), name: "Reference")
.theme(corporate)
comparison.show()The gallery uses the six observations in the complete notebook; the shorter code above uses four. Reference values are supplied rather than fitted. The company name identifies the theme; it does not add a logo. Include the organization in the title or caption when the artwork must show it.
Light, dark and custom palettes
plot.theme("light"), plot.theme("dark") and plot.theme("auto") return ChartTheme. Explicit light and dark choices are stable presentation decisions; auto follows the host where supported. Attach a theme per chart so execution order does not silently change later figures.
let dark = plot.theme("dark").palette(
colors: List("#79D2E0", "#FFBC78", "#C6ACFF")
)
comparison.theme(dark).show()
comparison.theme(plot.theme("light")).show()Theme colors use checked hexadecimal values. Palette and company modifiers return new theme values. Legends, labels and annotations should explain meaning alongside color. A valid hexadecimal palette is not a contrast certification or evidence of perceptual uniformity.
Offline world, country and local maps
The optional world and usa packs supply Natural Earth 1:110m boundaries and require no online tiles, geocoding or map service. plot.world joins Natural Earth ADM0_A3 codes such as USA, CAN, FRA and NOR. These codes are not strictly ISO country codes; this source also includes KOS and SOL. Its 177 features follow the source geographic grouping rather than defining a sovereign country count.
plot.world(keys: List("USA", "CAN", "FRA"), values: List(12.0, 9.0, 15.0))
.title("Synthetic values on an offline world map")
.caption("Synthetic values; boundaries: Natural Earth 1:110m.")
.show()plot.usa joins uppercase two letter postal codes for 50 states and the District of Columbia. Alaska and Hawaii retain their geographic positions; the county and place catalogues below provide detail for all 50 states and DC.
plot.usa(keys: List("CA", "CO", "NY", "TX"), values: List(18.0, 12.0, 15.0, 9.0))
.title("Synthetic values for four USA states")
.caption("Synthetic values; other states have no data, not zero.")
.theme(corporate)
.show()Regional boundary catalogue
plot.map(region: String, keys: List, values: Any) adds an explicit catalogue selection. The regional catalogues below have String code, name, parent_code and kind feature properties; the constructor joins code, with one supplied value per distinct key. The existing world and usa ids are also accepted, using their original ADM0_A3 and postal properties respectively. plot.boundaries(region: String) returns the selected installed GeoJSON as String text for inspection or use with plot.choropleth. All these maps run offline.
| Catalogue id | Administrative coverage | Join keys and examples |
|---|---|---|
chile | All 16 regions of Chile | ISO 3166 to 2 Strings: CL-RM Metropolitana de Santiago, CL-VS Valparaíso, CL-NB Ñuble |
argentina | 23 provinces and Ciudad Autónoma de Buenos Aires | ISO 3166 to 2 Strings: AR-B Buenos Aires province, AR-C Buenos Aires city, AR-X Córdoba |
europe | 53 Natural Earth country/map units in a bounded European extent | Natural Earth ADM0_A3: FRA, DEU, ESP, ITA, GBR; geographic Europe rather than EU membership |
mexico | 31 states and Mexico City, retaining the pinned source's 32 named federal entities | Source ISO style Strings: MX-JAL Jalisco, MX-NLE Nuevo León, MX-DIF Mexico City (legacy key) |
canada | All 10 provinces and 3 territories in the source | ISO 3166 to 2 Strings: CA-BC British Columbia, CA-ON Ontario, CA-QC Québec, CA-NU Nunavut |
usa.<state>.counties | Census county or county equivalent layers for all 50 states and DC; lowercase postal code replaces <state> | Five digit GEOID Strings: 08013 Boulder County, 06085 Santa Clara County, 48201 Harris County |
usa.<state>.places | Census incorporated-place/CDP layers for all 50 states and DC | Seven digit GEOID Strings: 0807850 Boulder, 0667000 San Francisco, 0644000 Los Angeles, 0655282 Palo Alto, 3651000 New York, 1571550 Urban Honolulu, 4835000 Houston |
County and place boundaries answer different questions. Boulder city and Boulder County have different boundaries. Palo Alto is a city in Santa Clara County; it has its own place boundary. A Census place can be an incorporated city or a census designated place, depending on the feature. Neither county nor place boundaries define a metropolitan statistical area, neighborhood, postal ZIP area, street network or service catchment. Match data to the exact level and vintage before joining. These are area polygons, not city point markers.
Chile and Argentina use generalized Natural Earth 1:10m admin 1 boundaries from the pinned June 2, 2022 source commit. Chile is clipped to longitude −76° to −66° and latitude −56° to −17°; Argentina to longitude −74° to −53° and latitude −56° to −21°. They cover continental territory and nearby islands within those extents, excluding remote islands and Antarctic claims.
Mexico and Canada use the same pinned Natural Earth 1:10m admin 1 snapshot. Their named administrative units retain all source parts without a continental clip. Mexico excludes one unnamed offshore source pseudo unit (MX-X01~) that has no valid administrative join key; it is not assigned to a state by guesswork. Mexico City retains source key MX-DIF and source label “Distrito Federal”; this is a legacy source identifier, not a claim that it is the current ISO key or administrative name. Canada includes the source Arctic islands in its provincial/territorial features. These layers provide state/province/territory boundaries, not Mexican municipalities or Canadian city boundaries.
Europe uses Natural Earth 1:10m countries from that same source snapshot: its Europe grouping plus Cyprus and Turkey, clipped to longitude −25° to 45° and latitude 34° to 72°. The 53 map units include microstates and country parts; this is a geographic display extent, not EU membership or a set of full national territories. It does not yet provide NUTS, provinces, municipalities or overseas territory detail.
All 50 states and DC have separate county and place catalogues from 2025 US Census 1:500,000 cartographic boundary files, transformed from NAD83 to WGS84 longitude/latitude and simplified with shared edges preserved. The finer regional assets support city viewports within bounded resource budgets. Use lowercase postal codes such as usa.ny.places, usa.hi.counties or usa.tx.places. Gaps outside Census places are outside place coverage, distinct from included places with no supplied value. These generalized layers support statistical previews rather than street maps or surveyed boundaries. The source manifest records exact hashes, snapshot dates, coordinate transformations and simplification. Pinned boundaries do not imply that an administrative boundary is current today.
plot.map(region: "chile", keys: List("CL-RM", "CL-VS", "CL-NB"), values: List(12.0, 9.0, 7.0))
.title("Synthetic values in three Chilean regions")
.caption("Synthetic index; Natural Earth 2022 snapshot; absent regions have no data.")
.show()
plot.map(region: "argentina", keys: List("AR-B", "AR-C", "AR-X"), values: List(11.0, 8.0, 10.0))
.title("Synthetic values in Argentine provinces and city")
.caption("Synthetic index; Natural Earth 2022 snapshot; province and city use distinct keys.")
.show()
plot.map(region: "europe", keys: List("FRA", "DEU", "ESP", "ITA", "GBR"), values: List(12.0, 15.0, 9.0, 10.0, 14.0))
.title("Synthetic country values in Europe")
.caption("Synthetic index; Natural Earth 2022 snapshot; Europe is broader than the EU.")
.show()
plot.map(region: "usa.co.counties", keys: List("08013"), values: List(12.0))
.title("Synthetic value for Boulder County, Colorado")
.caption("Synthetic index; Census 2025 county GEOID 08013; distinct from Boulder city.")
.show()
plot.map(region: "usa.ca.places", keys: List("0667000", "0644000", "0655282"), values: List(12.0, 18.0, 9.0))
.title("Synthetic values for three California cities")
.caption("Synthetic index; Census 2025 places: San Francisco, Los Angeles and Palo Alto.")
.show()Every country, selected independently
The global country catalogue has one optional outline pack for each of 249 ISO coded countries and territories, covering all 248 UN M49 country/area entries plus Taiwan. All 193 UN members and the two UN observer states are represented. Another 20 source map units have separate source.* identities instead of invented ISO codes. This is a geographic coverage inventory, not a declaration of sovereignty. The country/territory and Chile region catalogue records exact pack IDs, names, joins, continental groupings and territorial coverage.
Use country.<code> with a lowercase three letter country code in the ID and the matching uppercase key in the join. For example, country.fra selects France and joins FRA; country.jpn selects Japan and joins JPN. These independent packs contain national outlines, including small countries omitted by the older 1:110m world overview. Coverage spans Europe, Asia, Africa, Oceania, Central America, the Caribbean and the rest of the Americas.
National outlines and administrative regions answer different questions. country.chl contains Chile's national outline. The existing chile pack contains its 16 administrative regions within the documented continental clip. chile.region.rm contains only the Metropolitana de Santiago region from that same administrative layer, retaining key CL-RM. Other Chile region packs use the lowercase suffix of their existing region key, such as chile.region.nb for CL-NB and chile.region.vs for CL-VS. Region selection adds no province, commune or street geometry.
import aner.plot
// Only chile.region.rm is needed: no chile, country.chl or world pack.
plot.map("chile.region.rm", keys: List("CL-RM"), values: List(12.0))
.focus("CL-RM")
.projection("lambert_azimuthal_equal_area")
.title("Metropolitana de Santiago: one region, one optional pack")
.caption("Synthetic index; pinned Natural Earth 2022 administrative geometry.")
.show()
// Only country.jpn is needed: no world or Asia overview is opened.
plot.map("country.jpn", keys: List("JPN"), values: List(9.0))
.focus("JPN").projection("auto")
.title("Japan: independently installed national outline")
.caption("Synthetic index; national outline, without prefecture or street detail.")
.show()These native SVG previews come from the same selected pack chart code. Each geometry travels with its saved output for offline viewing.
Choosing a smaller pack reduces both installed data and parsed geometry. By comparison, .focus("CL-RM") on plot.map("chile", ...) fits a viewport on an already loaded 16 region chart; it retains that complete chart's geometry and values. Use chile.region.rm when the analysis only needs that region. Importing aner.plot loads no map geometry; selecting one country or Chilean region opens only its selected asset. Installing other packs does not preload them. Retained charts own their geometry, so retain only the charts needed by a long running analysis or restart a notebook session to release its values.
Download the country and Chile region source, the .anernb notebook. Each uses the same chart building code and explicitly names the pack required by each cell. The complete example uses France, Japan, Kenya, Australia, Guatemala, Chile's outline and a single Chilean region; running only one chart requires only its own pack. The matching development runtime and notebook integration remain required. Constructed SVG and supported notebook/HTML snapshots carry their selected geometry and can be viewed offline; rerunning the source needs its selected installed pack again.
All South American countries
The south.america pack supplies a continental overview. Each of the twelve sovereign countries has an independent pack and administrative region catalogue:
| Catalogue and pack | First administrative level | Example exact key |
|---|---|---|
argentina | 23 provinces and the autonomous city | AR-B Buenos Aires province |
bolivia | 9 departments | BO-L La Paz |
brazil | 26 states and the Federal District | BR-SP São Paulo |
chile | 16 regions | CL-RM Metropolitana de Santiago |
colombia | 32 departments and Bogotá | COL-1399 Bogotá |
ecuador | 24 provinces | EC-P Pichincha |
guyana | 10 regions | GY-DE Demerara Mahaica |
paraguay | 17 departments and Asunción | PY-ASU Asunción |
peru | 26 source units, including Callao and separate Lima units | PER-587 Lima Province |
suriname | 10 districts | SR-PM Paramaribo |
uruguay | 19 departments | UY-MO Montevideo |
venezuela | 25 named source units, including capital and federal dependencies | VE-A Distrito Capital |
plot.map("south.america", List("BRA", "CHL", "ARG"), List(18, 14, 12))
.projection("lambert_azimuthal_equal_area")
.title("South America: synthetic country values").show()
plot.map("brazil", List("BR-SP"), List(10))
.focus("BR-SP").title("São Paulo: synthetic state value").show()Install only south.america for the overview, or only brazil for the second chart. The complete South America source and notebook demonstrate the overview and all twelve administrative layers using synthetic values. The overview uses exact country keys such as BOL, BRA, COL, ECU, GUY, PRY, PER, SUR, URY and VEN, alongside ARG and CHL.
These layers retain a pinned Natural Earth 2022 snapshot. They are generalized display boundaries, with source territorial depictions rather than an assertion of sovereignty or present legal status. The continental overview separately keys French Guiana, the Falkland Islands and the source indeterminate Brazilian Island and Southern Patagonian Ice Field. The twelve country values do not assign data to those units. Chile and Argentina keep their documented continental clips. Other country layers retain their source parts, including Ecuador's Galápagos Islands. Named Colombian and Venezuelan administrative units exclude unnamed offshore source pseudo units.
Preserve the codebook keys rather than guessing modern ISO codes. The source repeats CO-CUN for Bogotá and Cundinamarca, and PE-LIM for Lima Province and Lima department. The catalogues resolve those collisions with the unambiguous source IDs COL-1399 for Bogotá and PER-587 for Lima Province; these two are source identifiers, not ISO codes. plot.boundaries("colombia") and plot.boundaries("peru") expose the retained properties for inspection. Data vintage, disputed areas and administrative level should match the observations before joining.
Mexico and Canada: regional maps and focus
Use Albers for the broad national statistical views and local Lambert azimuthal equal area for a focused administrative unit:
let mexico = plot.map("mexico", List("MX-DIF", "MX-JAL", "MX-NLE"), List(8.0, 12.0, 10.0))
mexico.projection("albers").title("Mexico: synthetic federal-entity values").show()
mexico.focus("MX-DIF").projection("lambert_azimuthal_equal_area")
.title("Mexico City: legacy source key MX-DIF").show()
let canada = plot.map("canada", List("CA-BC", "CA-ON", "CA-QC"), List(9.0, 14.0, 11.0))
canada.projection("albers").title("Canada: synthetic provincial values").show()
canada.focus("CA-ON").projection("lambert_azimuthal_equal_area")
.title("Ontario administrative extent").show()The complete Mexico/Canada source and notebook include source/vintage captions and one chart per output cell. Focus enlarges an existing administrative polygon; Mexico City here is a federal entity boundary and Ontario is a province. No additional city, neighborhood or street geometry is inferred.
City zoom, extents and regional projections
Use .focus(key: String, padding: Float64 = 0.15) to fit one existing boundary feature. Padding adds the declared fraction of its longitude/latitude span on each side; valid padding is 0.0…2.0. The key uses this chart's join property, so Boulder city is "0807850" on usa.co.places, while Boulder County is "08013" on usa.co.counties. A feature can be focused even when it has no supplied value. Focus fits all feature parts, including offshore islands. San Francisco includes the Farallon Islands; a subsequent urban extent enlarges its mainland area. Focus keeps surrounding boundaries and their no data status; it does not select a subset of the statistical observations.
Use .extent(west: Float64, south: Float64, east: Float64, north: Float64) for a reproducible comparison viewport. Coordinates are WGS84 longitude/latitude degrees. west > east selects an antimeridian crossing interval. south must be below north; longitudes/latitudes must be finite and within ±180°/±90°. The overload .extent(bounds: GeoExtent) accepts a checked value constructed by aner.geo. Drawing requires at least 0.00000001° of span on each axis; the geographic datatype can represent narrower extents that cannot be plotted at this precision. Each modifier returns a new chart. The most recent extent or focus sets the view, while the full chart's color range is retained so zooming does not silently recolor the same value.
import aner.plot
import aner.geo
let california = plot.map("usa.ca.places",
keys: List("0667000", "0644000", "0655282"), values: List(12.0, 18.0, 9.0))
california.focus(key: "0667000")
.extent(west: -122.56, south: 37.68, east: -122.32, north: 37.84)
.title("San Francisco urban extent")
.caption("Synthetic index; Census 2025; urban viewport excludes offshore Farallon parts.").show()
california.focus(key: "0644000").title("Los Angeles: municipal boundary").show()
california.focus(key: "0655282").title("Palo Alto: municipal boundary").show()
plot.map("usa.co.places", List("0807850"), List(8.0))
.focus(key: "0807850", padding: 0.20)
.projection("lambert_azimuthal_equal_area")
.title("Boulder city, Colorado")
.caption("Synthetic index; generalized Census 2025 place boundary, not Boulder County.")
.show()
let bayArea = geo.extent(west: -122.65, south: 37.20, east: -121.70, north: 38.15)
california.extent(bounds: bayArea).projection("auto")
.title("Bay Area places in an explicit shared viewport").show()The callable module forms plot.focus(chart, key, padding), plot.extent(chart, ...) and plot.projection(chart, name) have the same immutable behavior. These modifiers require a geographic chart. .summary() and the SVG description disclose the viewport and effective projection, including automatically derived regional parameters. Reuse exactly the same explicit extent/projection for comparable geographic views; a common color scale across separately constructed charts remains a separate feature.
.projection(name) | Use and limits |
|---|---|
"auto" | Small/city extents use local Lambert azimuthal equal area; wider same hemisphere midlatitude regions use Albers; tropical/polar regional extents use Lambert azimuthal equal area; world scale extents use equirectangular |
"lambert_azimuthal_equal_area" | Local/city, island and compact regional views; centered on the viewport, longitude span under 180° |
"albers" | Wider same hemisphere state/regional statistical views; standard parallels at one sixth and five sixths of the latitude span; regional longitude span must be under 180° |
"mercator" | Conformal drawing with strong area distortion toward the poles; extents containing a pole fail |
"equirectangular" | Simple geographic preview and global overview; substantial shape/area distortion away from the appropriate latitude |
Calling focus or extent enables auto unless a projection was explicitly selected. Boundary charts without a viewport or explicit projection keep their equirectangular overview; standalone geographic scatter charts use auto with their fitted point extent. An explicit projection remains selected across later viewport changes. Source polygons are clipped to the geographic extent before projection, and the display is fitted to that view. Map .annotate(x, y, text) uses WGS84 longitude/latitude and follows the same projection and viewport clipping. Antimeridian source rings still need their GeoJSON split. Alaska and Hawaii retain their actual geography; an Alaska wide extent can deliberately cross the dateline. Drawing extents must span at least 1e-8 degrees on both axes; smaller valid GeoExtent data values cannot be used as map viewports. Projected drawing is bounded to 1,000,000 densified coordinates. The compatible VS Code notebook renderer adds interactive pan and zoom inside this initial view; see below. Insets remain future work.
These are spherical display projections with parameters derived from the current viewport, not EPSG CRS transformations or projected analysis coordinates. Albers and Lambert azimuthal equal area preserve area in their spherical mathematical models; generalized source geometry, spherical Earth assumptions and SVG pixel size limit analytical interpretation. See the PROJ Albers and Lambert azimuthal equal area references for projection families. Aner does not link PROJ or claim an ellipsoidal EPSG implementation. Calculate distance/area with an explicitly specified analysis method and appropriate source geometry.
New York, Hawaii and Texas use the same API as every other state:
plot.map("usa.ny.places", List("3651000"), List(11.0))
.focus("3651000").title("New York City").show()
plot.map("usa.hi.places", List("1571550"), List(7.0))
.focus("1571550").title("Urban Honolulu Census place").show()
plot.map("usa.tx.places", List("4835000"), List(13.0))
.focus("4835000").title("Houston, Texas").show()
plot.map("usa.tx.counties", List("48201"), List(13.0))
.projection("albers").title("Texas counties; synthetic Harris County value").show()The complete city source and notebook are examples/plot_city_views.aner and examples/notebooks/plot_city_views.anernb. The notebook separates each city into a bounded output cell. Zoom enlarges the installed municipal geometry; it cannot recover detail removed by source generalization, add streets or define neighborhoods.
Geographic observations: positions, labels and value colors
Use plot.geo_scatter(positions: List, values: Any[, labels: List]) to draw checked GeoPosition observations without loading any map pack. Use .add_points(positions: List, values: Any[, labels: List]) on an existing geographic chart to overlay them on installed or caller supplied boundaries. The module form is plot.add_points(chart, positions, values[, labels]). Positions are always WGS84 longitude/latitude; an arbitrary numeric pair or a projected easting/northing cannot substitute for GeoPosition.
import aner.plot
import aner.geo
let observations = List(
geo.position(longitude: -105.2705, latitude: 40.0150),
geo.position(longitude: -105.2500, latitude: 40.0300))
let values = List(8.0, 12.0)
let names = List("Illustrative site A", "Illustrative site B")
// No boundary pack needed; finite positions and synthetic values only.
plot.geo_scatter(positions: observations, values: values, labels: names)
.point_sizes(values: List(10.0, 40.0), max_radius: 14.0)
.point_labels("avoid")
.extent(west: -105.35, south: 39.95, east: -105.18, north: 40.10)
.projection("lambert_azimuthal_equal_area")
.title("Illustrative Boulder observations").show()
// Optional usa.co pack adds the municipal context.
plot.map("usa.co.places", List("0807850"), List(20.0))
.add_points(positions: observations, values: values, labels: names)
.point_sizes(values: List(10.0, 40.0), max_radius: 14.0)
.focus("0807850")
.title("The same observations over a city boundary").show()The nonempty position List and numeric values must have equal lengths, with at most 100,000 observations per chart. Values use the finite numeric vector contract above. Labels are optional: omit them or pass List() to show points without text; otherwise supply one String per position. Text is escaped in SVG, and each marker's tooltip metadata retains its label when present, WGS84 longitude, latitude and full supplied numeric value. Each label permits 4,096 UTF-8 bytes, with a combined 1 MiB label budget across point additions. Coincident points remain separate observations, so overplotting can hide records.
Marker color maps the supplied value onto a continuous scale. The legend titles distinguish Points from Regions when both are present. All point observations in one chart share a point color domain, including observations appended with later add_points calls. Polygon values use an independent color domain. Extent, focus and projection changes preserve both domains, so a zoom does not recolor retained observations. Separately constructed charts can still choose different domains. Explicit shared color limits remain future work.
Marker area and label placement
Geographic points initially use a uniform radius of 4 SVG pixels. Call .point_sizes(values[, max_radius]) after adding all observations to encode a separate numeric variable by circle area. Supply exactly one finite, nonnegative numeric value per point; the numeric vector input contract above applies. The optional maximum radius defaults to 14 pixels and must be between 1 and 64 pixels. With supplied maximum m > 0, each radius is max_radius * sqrt(value / m): doubling a value doubles marker area. A zero value gives radius zero, so its marker is invisible; an all zero size vector gives all markers radius zero. Label and tooltip metadata still retain those observations. Size values can differ from color values, and signed color values remain valid.
The size domain includes all chart points, including points outside the current extent. Extent, focus and projection changes retain this domain and the maximum pixel radius. Different charts normalize independently, so the same numeric value need not have the same area across separately constructed charts. State the size variable and its units in the caption; these drawing sizes do not estimate geographic land area. The proportional size legend shows zero as hidden, one quarter of the maximum value and the maximum, or an explicit message for an all zero vector. Marker tooltip metadata retains the supplied size value. The legend needs additional layout space; a chart that is too small for it fails with a diagnostic. Increase the chart size or reduce max_radius. .point_size(radius) restores uniform sizing with a finite radius between 0 and 64 pixels and clears the size mapping. Appending points after point_sizes is rejected: append first and set the complete size vector last, or call point_size before appending and then supply a new complete vector.
The default .point_labels("avoid") tries eight deterministic nearby positions for each visible label, in observation order. A bounded spatial grid checks conservative text boxes against previously placed labels, visible point markers and manually placed annotation boxes, keeping the label boxes inside the map frame. Labels that have no available candidate are hidden. This improves legibility without moving or removing observations; it is not a guarantee that every label will fit. Text may be abbreviated to the available view width, while the complete supplied text remains in marker tooltip metadata. Placement is computed again for the current chart dimensions, projection and extent, so zooming can change which labels fit. The SVG description discloses the placement mode; a hidden label count is not reported.
Use .point_labels("all") when every eligible label should be drawn even if labels overlap, or .point_labels("none") to suppress point text while retaining marker and tooltip metadata. These controls apply to geographic point labels. They do not reposition manually placed annotations; automatic polygon labels remain future work. The implementation uses native SVG layout with no network, font download, tile service or additional map pack. Points without a boundary chart need no pack at all.
A standalone point chart automatically fits the shortest longitude interval containing its positions, including a dateline crossing, and adds geographic padding. Its default projection is auto; an explicit extent and projection make comparison viewports reproducible. Points and boundary polygons use the same display projection and viewport. Adding observations does not load another pack. A boundary chart retains its viewport; set an explicit extent when observations lie beyond that view. A standalone point chart refits its automatic extent to include appended observations. An explicit extent remains fixed for either chart. .focus fits a boundary key and needs a boundary chart; a standalone point chart has no region keys. Geographic annotations and point labels are clipped with the view. These are drawing operations: no point in polygon assignment, geocoding, spatial aggregation, missing value filtering or CRS transformation is inferred.
The complete point source and matching notebook show proportional areas and label placement in a pack free Americas view plus Boulder, San Francisco/Palo Alto, Mexico City and Toronto overlays. They use illustrative locations and synthetic values. Only the overlay examples need usa.co, usa.ca, mexico and canada; exported SVGs retain their marks, placed labels and tooltip metadata for offline viewing.
Interactive notebook maps
In the updated Aner VS Code notebook extension, geographic .show() outputs and bare chart expressions support pan and zoom automatically. This includes standalone geo_scatter, installed pack maps and custom GeoJSON choropleths. Run the interactive Boulder notebook with the matching native runtime and extension. Its first chart needs no map pack; its second uses only usa.co. The source example produces the same initial charts.
Use +, − and Reset above the map. Drag inside the map to pan, double click to zoom in, or hold Ctrl/Cmd while scrolling to zoom around the pointer. With the map focused, +/− zoom, arrow keys pan, and Home resets. Ordinary wheel scrolling continues to scroll the notebook. Navigation is bounded to the chart's initial geographic extent, including an extent selected by .focus(...) or .extent(...). To explore several cities in one map, begin with a shared regional extent, then zoom and pan within it. Reset restores that initial view.
Marker radii and label text retain their drawing size as boundaries and point positions move. Point colors and proportional size domains remain those of the complete chart. The default point_labels("avoid") recomputes placement after each viewport change, so labels hidden in a crowded overview can appear when zoom provides space. Labels may hide again when space is lost. Placement retains the same deterministic input priority and eight nearby candidates; coincident positions can remain crowded at every zoom level. point_labels("all") permits overlap and point_labels("none") suppresses point text throughout navigation. Full point labels and values remain in tooltip metadata.
Projection parameters stay fixed from the initial view during interaction. This keeps points and boundaries aligned while panning and preserves the chosen spherical drawing projection. Pan and zoom do not change the stored Chart, its extent, its coordinates or its statistical values. Use explicit .extent(...) and .projection(...) calls and rerun the cell when a chosen viewport should be reproducible in source. plot.svg(chart) and .save("figure.svg") export the native static view; they do not capture a transient notebook pan or zoom.
The renderer and scene data are local. It makes no tile, font, geocoder or other network requests and does not call the native session while navigating. Boundary geometry comes only from a pack explicitly loaded when constructing the chart or from caller supplied GeoJSON. Saving .anernb outputs retains the scene and its static SVG fallback, so saved maps can be reopened and navigated offline with the compatible extension even without a running kernel or the original pack. Rerunning boundary chart code still requires its matching pack. View changes are temporary; reopening starts from the saved initial scene.
Interactive scenes have a separate bounded payload budget. If a scene exceeds its 2 MiB limit or would exceed the 4 MiB cell display envelope, the output retains the static SVG instead. No observations are sampled to make a scene fit. Individual geographic and linked charts use static SVG in the optional Jupyter adapter; their interactive renderer is supplied by the Aner VS Code extension. The separate plot.site_dashboard recipe also has the sandboxed Jupyter HTML view described above. Install the matching runtime and extension to enable it.
Checked positions for analysis
import aner.geo adds immutable GeoPosition and GeoExtent. Construct geo.position(longitude: -105.2705, latitude: 40.0150) for an illustrative Boulder location. The coordinates remain WGS84 longitude/latitude when a map's display projection changes. geo.great_circle_distance(a, b) returns Quantity<m> using a declared spherical approximation; import aner.units to annotate or convert that quantity. Point<degC> continues to mean an affine temperature reading. Geographic points, projected metric positions, feature IDs and polygon boundaries have different contracts. The checked position types support this drawing workflow. A broader columnar spatial data design remains future work.
Retrieve the canonical GeoJSON when an explicit property join is useful:
let chileBoundaries = plot.boundaries(region: "chile")
plot.choropleth(geojson: chileBoundaries, property: "code", keys: List("CL-NB"), values: List(7.0))
.caption("Synthetic index for Ñuble; source and vintage are in the catalogue.")
.show()Chile's complete region key list is:
| Code | Region | Code | Region |
|---|---|---|---|
CL-AP | Arica y Parinacota | CL-TA | Tarapacá |
CL-AN | Antofagasta | CL-AT | Atacama |
CL-CO | Coquimbo | CL-VS | Valparaíso |
CL-RM | Metropolitana de Santiago | CL-LI | Libertador General Bernardo O'Higgins |
CL-ML | Maule | CL-NB | Ñuble |
CL-BI | Biobío | CL-AR | La Araucanía |
CL-LR | Los Ríos | CL-LL | Los Lagos |
CL-AI | Aysén del General Carlos Ibáñez del Campo | CL-MA | Magallanes y de la Antártica Chilena |
Region names can refer to broader territories than this continental preview. In particular, CL-MA does not add an Antarctic territorial claim map; remote Pacific islands fall outside the Chile extent. The Argentine preview likewise does not map Antarctic or other claimed territories outside its extent.
Argentina's complete province/city key list is:
| Code | Province or city | Code | Province or city |
|---|---|---|---|
AR-B | Buenos Aires province | AR-C | Ciudad Autónoma de Buenos Aires |
AR-K | Catamarca | AR-H | Chaco |
AR-U | Chubut | AR-X | Córdoba |
AR-W | Corrientes | AR-E | Entre Ríos |
AR-P | Formosa | AR-Y | Jujuy |
AR-L | La Pampa | AR-F | La Rioja |
AR-M | Mendoza | AR-N | Misiones |
AR-Q | Neuquén | AR-R | Río Negro |
AR-A | Salta | AR-J | San Juan |
AR-D | San Luis | AR-Z | Santa Cruz |
AR-S | Santa Fe | AR-G | Santiago del Estero |
AR-V | Tierra del Fuego | AR-T | Tucumán |
Each optional map pack retains its exact source version, coverage and attribution notices.
For custom boundaries, load licensed local GeoJSON with plot.geojson(path: "regions.geojson"), then join a stable String property with plot.choropleth. GeoJSON coordinates are longitude, latitude, in that order. Polygon holes and MultiPolygon parts are supported. Preserve identifiers with leading zeros. Confirm join coverage, denominators and geographic vintage before interpreting results. Missing regions are no data, never fabricated zeros.
Spherical regional display projections and city viewports are available as described above. They do not provide a projected analysis CRS or precise area/distance measurements. Supplied rings crossing the antimeridian must already be split; unsplit edges are rejected except the legitimate Antarctic pole boundary.
Boundary source and attribution
The regional catalogue additionally records the attribution, source snapshots and normalization for Chile, Argentina, Europe, Mexico, Canada, and county/place layers for all 50 states and DC in the source metadata and attribution notices carried by each pack.
The world and USA state layers are made with Natural Earth, whose terms of use place the geographic data in the public domain. Credit includes Tom Patterson, Nathaniel Vaughn Kelso and contributors. The source is pinned at commit ca96624a56bd078437bca8184e78163e5039ad19, June 2, 2022. The official 110m layer pages identify version 5.1.1; the repository version at that commit reads 5.2.0-pre.
| Boundary file | Features | SHA256 |
|---|---|---|
world-110m.geojson | 177 | 6866c877d39cba9c357620878839b336d569f8c662d3cfab4cb1dbe2d39c977f |
usa-110m.geojson | 51 | 0067dec6a2c4f9c7a644bf7a9a46163d8d881595953326d0c67d89934190aefe |
Notebook placement and export
Use .show() in the cell whose analysis the chart supports. Each call emits a separate output in execution order. In a shared native notebook session, a bare chart expression also displays; let stores a chart without displaying it. Inside loops and functions, call .show() explicitly. Put explanatory Markdown immediately before or after the producing cell.
Notebook outputs are saved historical results. Editing code or changing later values does not recompute a chart. Restart and run cells in order to verify a fresh analysis. Saving notebook outputs preserves static SVG and any bounded interactive map, linked chart or spatial scene, not live runtime variables. Saved scenes reopen offline with the compatible extension and need no running session; rerunning boundary code requires its map pack. The optional native Jupyter adapter uses the same SVG through its MIME display mechanism.
For a shareable figure, call comparison.save("response-comparison.svg") with a fresh filename. SVG keeps marks and text scalable. Direct Chart.save PNG and PDF file writers and font embedding are not implemented. For PDF reports, use the optional aner.pdf chart bridge described below. Spatial viewers provide local PNG and vector SVG downloads of the current view, and saved interactive HTML retains captured frames and view state; interpolated animation remains future work. Linked selection runs in the compatible notebook renderer and the prepared HTML explorer; SVG export remains the initial static figure.
Errors, bounds and next steps
Mismatched lengths, unsupported ranks, invalid colors, nonfinite values and malformed geometry produce diagnostics. Data ingestion, table aggregation, fitting and uncertainty estimation remain explicit upstream decisions.
Limits are 100,000 observations, 32 series, 250 bar categories or histogram bins, 10,000 heatmap cells, 10,000 geographic features or joins, 100 annotations and 32 palette colors per chart. Text permits 4,096 UTF-8 bytes. Width ranges from 320 to 4,096 pixels, and height from 240 to 4,096 pixels. GeoJSON permits 8 MiB and 100,000 coordinates within parser limits. SVG output is bounded to 32 MiB; notebook envelopes additionally permit at most 64 charts and 4 MiB per cell. Interactive map, linked chart and spatial scenes permit 2 MiB and fall back to SVG when the extra scene cannot fit. Other exceeded bounds produce a diagnostic instead of silent sampling.
The implemented families are line, scatter, bar, histogram, box, heatmap, choropleth and geographic scatter. World, USA and the regional map catalogue are convenience constructors for choropleths. Geographic points support proportional areas and collision aware labels. Data scientists also need shared color/marker-size limits, join diagnostics, rates, uncertainty and spatial operations; these remain planned additions, subject to explicit scientific and data contracts. Figure grids, facets, temporal scales, statistical intervals, sequential and diverging scale controls, general CRS transformations, 3D and further exporters remain future work.
Native charts in PDF reports
Requires Aner 0.0.10 or greater and PDF module 0.1.1 or greater.
Import aner.pdf alongside aner.plot, then call
pdf.plot(report, chart, width: 400.0, height: 240.0). The chart is captured
as an immutable static vector snapshot, without an intermediate image file.
Interactive controls remain in the notebook or HTML export.
See PDF reports and extraction for the
complete report workflow, template metadata and executable examples.
See the complete callable index for the native module and method name catalogue.