spec

package
v2.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 19 Imported by: 0

README

ntcharts/spec

Package spec defines a neutral, surface-agnostic chart specification for ntcharts. A single Spec value describes a chart (type, axes, data, options, theme) and can be rendered to multiple surfaces from the same source of truth:

  • Terminal — via spec.Build(s) → an ntcharts model (*barchart.Model, *linechart.Model, *timeserieslinechart.Model, *heatmap.Model, …)
  • Web — via echarts.ToECharts(s) → a go-echarts/v2 chart (*charts.Bar, *charts.Line, …). This surface lives in its own module, github.com/NimbleMarkets/ntcharts/spec/echarts/v2 (directory spec/echarts), so the go-echarts dependency is only pulled in by programs that render to the web; terminal consumers of github.com/NimbleMarkets/ntcharts/v2/spec never see it. It is released alongside the root module with the spec/echarts/v2.X.Y tag.

Specs are JSON-marshalable so they can be persisted, transported over the wire, or authored in configuration files. Zero-valued option structs are omitted; pointer fields preserve explicit zero pins and precision. A series' values field is always emitted (null for a nil slice, [] for an empty non-nil slice), including OHLC series whose points live in ohlc.

OHLC volume panel

Set Options.Volume = true and supply OHLCPoint.V pointers:

volume := 12300.0
s := spec.Spec{
    Type: spec.ChartTypeOHLC, Width: 80, Height: 24,
    Options: spec.Options{Volume: true},
    Data: spec.Data{Series: []spec.Series{{Name: "Price", OHLC: []spec.OHLCPoint{
        {T: "2026-01-05", O: 100, H: 108, L: 97, C: 105, V: &volume},
    }}}},
}
built, err := spec.Build(s)
if err != nil { /* handle error */ }
model := built.(*spec.OHLCModel)
fmt.Println(model.View())
model.Resize(100, 30) // redraws both panels

JSON uses "v":12300 on a point and "options":{"volume":true}. V == nil means missing, while a pointer to zero means known zero; neither paints a terminal bar. Values must be finite and non-negative, even when the panel is disabled. Volume is valid only on OHLC specs. Both new fields are omitted at their zero values, preserving existing JSON.

With the option off, or with every V nil, Build returns the original *timeserieslinechart.Model and preserves its rendering. Otherwise it returns *spec.OHLCModel, with View, Draw, Resize(w, h) and an Update method that handles tea.WindowSizeMsg. It retains the spec for redraw; independent panel pan/zoom is not supported. Initial builds require at least seven rows and sufficient width for the axes. Resizing too small blanks the canvas; resizing larger restores both panels.

The terminal reserves roughly a quarter of the plot rows for volume. Both panels use the same time scale, Y-axis gutter, candle body width (1–7 columns), edge inset and up/down palette colours. Only the bottom panel has X labels. Volume has an independent linear scale from zero to the maximum observed V, with an SI maximum label (12.3k, 4.5M); price retains its configured Y scale.

echarts.ToECharts returns *charts.Kline. Web candles use ordered category slots labelled by UTC timestamps (so calendar gaps are compressed on web). With volume enabled it adds a lower grid, matching category axis and a volume bar series, preserves missing values as null, and links axis pointers and inside data zoom across both X axes. The default axis tooltip uses price-first series order followed by volume, without a JavaScript formatter. Any caller-added data zoom must also target []int{0, 1}. Both grids share fixed margins.

Run go run ./examples/ohlc-volume -html /tmp/ohlc-volume.html for a self-contained sample with weekend gaps, terminal rendering and optional HTML export.

Status

Chart type Build() (terminal) echarts.ToECharts() (web)
ChartTypeBar full — stacked + horizontal; categorical bar/line combo; grouped bars unsupported full
ChartTypeTimeSeries full full
ChartTypeLine full — connected braille lines on *linechart.Model scaffold
ChartTypeScatter full scaffold
ChartTypeHeatmap full scaffold
ChartTypeStreamline scaffold scaffold
ChartTypeSparkline full scaffold
ChartTypeOHLC full — candlesticks; optional volume panel on *OHLCModel full — candlesticks and optional volume grid
ChartTypeCanvas scaffold scaffold

Scaffolded chart types return a clear not yet implemented error today.

Pure multi-series ChartTypeBar is stacked-only in the terminal because barchart.Model has no grouped/side-by-side rendering mode: a Spec with more than one Series must set Options.Stacked = true, or Build returns an error instead of silently stacking series a caller may have expected to be grouped side by side. Options.Orientation = OrientationHorizontal renders horizontal bars via barchart.WithHorizontalBars() in the terminal. ToECharts() does not yet honour Options.Stacked or Options.Orientation for bar charts — every web bar chart renders as grouped, vertical bars regardless of these options; web stacking/orientation support is planned but not implemented.

ChartTypeOHLC is built on timeserieslinechart.Model the same way ChartTypeTimeSeries is: buildOHLC pushes open/high/low/close data sets keyed by each OHLCPoint's parsed time and draws candles with (*timeserieslinechart.Model).DrawCandleWithOpts, so candles render at time-scaled X positions across the full graph width — the same axis machinery (including labeled axes via XAxis.Format / YAxis.Format) as the timeseries surface. Candles are coloured by Theme.Palette[0] (up, close >= open) / Theme.Palette[1] (down), defaulting to #26a69a / #ef5350 when the palette does not set those slots. YAxis.Min / YAxis.Max follow the same one-sided pin rule as the line/scatter/timeseries surfaces (see "One-sided Y-axis pins" below). Candle body width is chosen automatically from chart density (autoCandleWidth): roughly an equal share of the graph width per candle, clamped so time-scaled neighbours on irregular calendars never overlap, forced odd, and capped at 7 columns so sparse charts still read as individual candles. Options.CandleStyle selects the rendering style: "" or CandleStyleLine renders box-drawing line runes (the default), CandleStyleBlock renders solid block bodies; unknown values are a Build error. Edge candles (those whose true time position would run their body into the axis or past the chart edge) are shifted inward (inset) up to half a body width so their whole body renders; nothing is clipped. There is no dropping of points for density — a Spec with more OHLC points than comfortably fit overdraws densely, exactly like any other dense timeseries, rather than discarding older candles. OHLC requires exactly one series; additional series return a Build error. Series.Color is ignored for OHLC because colours encode up/down direction.

Line, scatter, timeseries, and OHLC builders return an error when the requested dimensions leave no drawable columns or rows after allocating axes and labels. Singleton time ranges (including timestamps within the same millisecond) are widened by twelve hours on each side so their points remain visible.

Surface fidelity matrix

Not every Spec option is honoured identically (or at all) by both surfaces. This table reflects the current, real behaviour of Build() (terminal) and ToECharts() (web) — consult it before assuming an option "just works" on both:

Spec option Terminal (Build) Web (ToECharts)
Options.Stacked (bar) honoured — required (else error) when a bar Spec has more than one Series ignored — web stacking planned, not implemented
Options.Orientation (bar) honoured via barchart.WithHorizontalBars() ignored — always renders vertical bars
XAxis.Scale / YAxis.Scale = "log" honoured — Y for line, scatter, timeseries, ohlc; X for line, scatter. A Build error for X on timeseries/ohlc (time axis), for either axis on bar, heatmap, sparkline, and for any value or pin <= 0 — see "Logarithmic axes" below ignored — ToECharts() does not read scale yet and draws a linear axis
YAxis.Min / YAxis.Max, one-sided (line, scatter, timeseries, ohlc) honoured — see "One-sided Y-axis pins" below honoured — ECharts auto-scales the unset bound natively
Y2Axis / Series.YAxis = "right" (line, scatter, timeseries) honoured — a right-hand Y axis with the same pin, log and format rules as YAxis; its labels take the first right-hand series' colour; a Build error on bar, ohlc, heatmap, sparkline — see "Dual Y axes" below honoured for timeseries — an extended ECharts axis (position right) with Min/Max/Title; Format/Scale ignored like the left axis's; line/scatter are scaffold-only; on bar charts y2_axis and y_axis: "right" are ignored (a single left axis)
Series.Type = "bar" in a timeseries drawn as a braille line like any series, on the axis its y_axis names overlaid as real bars on the axis its y_axis names — no longer given its own axis implicitly (v2.8.0); set y_axis: "right" and a y2_axis for the old look
Theme.Palette[0] / [1] (ohlc) honoured — slot 0 = up candles, slot 1 = down candles; defaults #26a69a / #ef5350 when unset honoured — the same up/down slots colour candles and volume bars
Options.CandleStyle (ohlc) honoured — "" or CandleStyleLine renders box-drawing line runes, CandleStyleBlock renders solid block bodies; unknown values error ignored — terminal-only; ECharts renders native candlesticks
Series.OHLC count vs. chart width (ohlc) candles render at time-scaled X positions across the full graph width with an automatically chosen, density-based body width (odd, capped at 7); dense series overdraw rather than dropping points ordered category slots; ECharts chooses candle widths
YAxis.Min / YAxis.Max (bar) forwarded to barchart.WithMinValue() / WithMaxValue(); positive minima clamp to zero; a lone pin leaves the other bound auto-scaled by the model; explicit Min > Max is a Build error honoured (set directly on the ECharts Y axis)
YAxis.Min (sparkline) ignored — sparkline.Model has no Y-minimum concept, only WithMaxValue N/A — ToECharts() is scaffold-only
YAxis.Max (sparkline) honoured via sparkline.WithMaxValue() when set; otherwise auto-scales N/A — ToECharts() is scaffold-only
Data.Series (sparkline) requires exactly one — multiple series error (like grouped bars) N/A — ToECharts() is scaffold-only
XAxis.Format / YAxis.Format (line, scatter) honoured via XLabelFormatter / YLabelFormatter ignored — not wired into ToECharts()
XAxis.Format (timeseries) honoured only when Kind == "time"; other kinds are intentionally ignored (the X axis is time-valued) Layout is translated and applied unconditionally as the ECharts time-axis label template (Kind is not checked)
YAxis.Format (timeseries) honoured via YLabelFormatter ignored — not wired into ToECharts()
Theme.Gradient (heatmap) honoured — interpolated colour scale ignored — heatmap is ToECharts()-scaffold only
Heat.MinValue / Heat.MaxValue honoured independently; an unset bound is derived from the selected cells/matrix; inverted effective ranges error N/A — heatmap is scaffold-only
Heat.Matrix / Heat.Cells matrix rows are Y indices and columns are X indices; a nonempty matrix takes precedence over cells N/A — heatmap is scaffold-only
Data.XAxisData (bar, line, scatter, timeseries) resolves omitted point X values; explicit point X takes precedence honoured for bar and timeseries; line/scatter are scaffold-only
Data.Series / Series.Color (ohlc) exactly one series required; Series.Color ignored in favour of up/down palette slots exactly one series; up/down palette slots match terminal
Theme.Palette (bar, line, scatter, timeseries, sparkline) fallback for series without Series.Color honoured for bar and timeseries; other types are scaffold-only
XAxis.Format / YAxis.Format (bar, heatmap, sparkline) ignored ignored for bar; other types are scaffold-only
XAxis.Labels honoured for bar, categorical line/scatter, Combo, and heatmap; ignored by numeric/time builders honoured for bar; ignored for timeseries
YAxis.Min / YAxis.Max (heatmap) ignored — use Heat.MinValue / Heat.MaxValue for the colour domain N/A — heatmap is scaffold-only
DataPoint.Size ignored everywhere — accepted by the schema, drawn as fixed-size markers on every surface ignored everywhere
XAxis.Title / YAxis.Title / Y2Axis.Title ignored — no current ntcharts terminal model surfaces an axis title YAxis.Title honoured for bar, timeseries and OHLC; Y2Axis.Title honoured for supported dual-axis charts; XAxis.Title honoured for OHLC (on the bottom axis with volume) and categorical combos, ignored for plain bar and timeseries
YAxis.Labels (heatmap rows) honoured — drawn left of the plot, first label on the top row; other chart types ignore it ignored — not wired into ToECharts(); reserved for future grid-chart row labels
Title / Subtitle ignored — the terminal models draw no title; the host TUI is expected to place one (e.g. flint-tui's status line) honoured — ECharts title/subtitle
Options.ShowLegend / Options.ShowGrid ignored — no terminal model draws a legend or background grid honoured
Theme.Background / Theme.Foreground ignored — the terminal inherits the host's colours; only Theme.Palette (series colours) and Theme.Gradient (heatmap) are read Background honoured as the canvas colour; Foreground ignored
XAxis.Type validated ("", category, time, value) but not consulted — each terminal builder infers the axis kind from the chart type (timeseries/ohlc are time-valued, bar/heatmap categorical, line/scatter numeric) honoured for bar (category vs value); timeseries always time
Series.Type validated (empty or a known chart type), otherwise ignored; timeseries series all use braille lines "bar" inside a timeseries spec overlays real bars (see the row above for which axis)

Fields belonging to another chart family are ignored: Heat outside heatmaps, Series.OHLC outside OHLC, Series.Values for OHLC, and Data.Series for heatmaps. Options.Orientation / Stacked apply only to bars, Options.CandleStyle only to OHLC, and Theme.Gradient only to heatmaps. Sparklines ignore X coordinates and shared X data; OHLC uses each point's T.

One-sided Y-axis pins

YAxis.Min and YAxis.Max can be set independently. The rule, enforced the same way by buildLine, buildTimeSeries, buildScatter, and buildOHLC: a lone Min or Max pins that bound; the other, unset bound is derived from the series' actual Y data (for buildOHLC, the observed high/low across all OHLCPoints). Setting both pins both bounds explicitly, and setting neither leaves the chart fully auto-scaled. If the resulting (effective) minimum exceeds the (effective) maximum — e.g. pinning Min above the data's actual maximum — Build returns an error (spec: y_axis min %v exceeds max %v) instead of silently constructing an inverted range. ToECharts() achieves the equivalent one-sided behaviour natively: an unset opts.YAxis.Min/Max (an interface{}, omitempty) is left out of the JSON entirely, so ECharts auto-scales that side itself; ToECharts() does not currently validate an inverted pin.

For these four terminal chart types, equal explicit Min and Max return an error because they leave no drawable Y range. If a lone pin equals the data-derived opposite bound, only the unpinned side expands by one unit. Unpinned flat scatter/OHLC ranges expand by one unit on each side.

On a log Y axis (YAxis.Scale = "log") the same rule holds, evaluated on the real values: Min / Max are given in data units, a lone pin fixes that bound while the other comes from the data, equal pins and an inverted range are the same errors, and a pin <= 0 is an error of its own. Only the unpinned bound differs — it widens to a whole decade instead of sitting on the data's extreme. See "Logarithmic axes" below.

ChartTypeBar pins each bound directly on the model (barchart.WithMinValue / WithMaxValue), so a lone pin leaves the other bound to the model's own auto-scaling, which already tracks negative values below zero. Setting both with Min > Max is the same Build error as above. A positive bar Min clamps to zero because the native bar model always retains a zero baseline.

Logarithmic axes

XAxis.Scale and YAxis.Scale are "" / "linear" (ScaleLinear, the default) or "log" (ScaleLog, base 10). Validate rejects anything else. Linear specs build exactly as they did before the field existed.

Chart type y_axis.scale: "log" x_axis.scale: "log"
line, scatter honoured honoured
timeseries, ohlc honoured Build error — the X axis is time
bar, heatmap, sparkline Build error Build error

Bar, heatmap, and sparkline charts have no way to draw a log axis, so Build refuses rather than drawing a linear chart under a spec that asked for log.

  • Values must be positive. Any value <= 0 (or NaN / infinite) on a log axis is a Build error naming it, e.g. spec: y_axis scale "log" requires positive finite values; series "a" point 3 has y = 0. That covers every point's Y, each OHLC open/high/low/close, a pinned YAxis.Min / Max, and on a log X axis every resolved X — including the index fallback, whose first point is X = 0. Nothing is clamped, skipped, or substituted.
  • Range. An unpinned bound widens to a whole decade (floor(log10(min)) … ceil(log10(max))), so the axis ends on powers of ten; a pinned bound is used exactly. When that leaves no range (all values on one power of ten), each unpinned bound moves out one more decade. The X axis has no pins and always uses whole decades.
  • Labels. Format applies to the value as on a linear axis, so currency, SI, percent, and number formats work unchanged. With no Format, labels are three significant digits with trailing zeros dropped and a k/M/G/T suffix from 1000 up (1, 2.5, 0.001, 1k, 3.16M), falling back to exponent notation below 0.0001 and from 1e15; the charts' own default, a whole number, would label every tick below 1 as 0.
  • Ticks sit on powers of ten, on the row or column where each one falls, whatever the chart's size. Labels keep the models' usual minimum spacing (two rows; two columns for line and scatter), so when decades are closer than that every second (third, ...) one is labelled. When a range holds fewer than three powers of ten, 2× and 5× are added where they fit, and a range too narrow for two round values falls back to evenly spaced labels. A pinned bound that is not itself a round value is not labelled.
  • How it is drawn. Build sets the chart model's own scale (linechart.ScaleLog), so the returned model's ranges (ViewMinY(), MaxX(), …) are in data units and its zoom and pan work in decades. ChartTypeLine joins each series' points with braille lines in input order, using the same scale mapping as scatter. Single points draw as braille dots; separate series are never joined.

See ExampleBuild_logScale in example_test.go.

Dual Y axes

Line, scatter and timeseries charts can carry a second, right-hand Y axis. y2_axis describes it with the same fields and rules as y_axis (one-sided pins, log scale, label format, title; which surface honours each field is in the fidelity table above), and a series selects it with y_axis: "right" ("" or "left" is the main axis). A right-hand series without y2_axis fails Validate; y2_axis on another chart type fails Build. The two axes may use different scales. On the terminal the right axis's view follows the left one when zooming or panning (it has no view of its own — see linechart.Axis), and its labels take the colour of the first right-hand series.

{
  "type": "timeseries", "width": 60, "height": 12,
  "y_axis":  {"min": 0, "max": 1},
  "y2_axis": {"min": 5, "max": 20, "title": "Temperature"},
  "data": {"series": [
    {"name": "load", "values": [{"x": "2026-01-01T00:00:00Z", "y": 0.2}, {"x": "2026-01-01T01:00:00Z", "y": 0.5}]},
    {"name": "temp", "y_axis": "right",
     "values": [{"x": "2026-01-01T00:00:00Z", "y": 8}, {"x": "2026-01-01T01:00:00Z", "y": 9}]}
  ]}
}

See ExampleBuild_dualAxes in example_test.go. On the web, ToECharts extends the chart with a right-positioned axis and puts right-hand series (lines or bars) on it.

Layout

spec/
├── spec.go              Spec, XAxis, YAxis, Format, Data, Series, DataPoint,
│                         HeatData, OHLCPoint, Options, Theme, Validate
├── helpers.go            X-value coercion (exported PointX / PointTime; pointFloat / pointString)
├── format.go              FormatValue + Format.labelFormatter (number/percent/currency/si/time)
├── scale.go               log axis scale: supported chart types, value errors, decade ranges, default labels
├── gradient.go            Theme.Gradient hex-stop interpolation for heatmap colour scales
├── build.go               Build(s) -> ntcharts terminal model (includes buildOHLC, on timeserieslinechart.Model;
│                         exported DeriveBarLabels shared with the web surface)
├── example_test.go        runnable examples (bar, line, log scale, scatter, timeseries, heatmap, ohlc)
├── README.md              this file
└── echarts/               separate module github.com/NimbleMarkets/ntcharts/spec/echarts/v2
    ├── go.mod
    ├── echarts.go         echarts.ToECharts(s) -> go-echarts/v2 chart
    └── example_test.go    ExampleToECharts, ExampleToECharts_timeSeries

Schema v1 overview

  • XAxis / YAxis describe each axis: Title, Labels, Format (label formatting), and Scale ("" / "linear", or "log" for a base-10 logarithmic axis — see "Logarithmic axes" above for which chart types honour it). XAxis.Type is XAxisCategory, XAxisTime, or XAxisValue (inferred from chart type when empty). YAxis adds Min/Max to pin the range: a lone Min or Max pins that bound while the other is data-derived, both pin an explicit range, and neither leaves the chart fully auto-scaled — see "One-sided Y-axis pins" above for the full rule and its edge cases. Y2Axis (a pointer; nil means one axis) describes an optional right-hand Y axis, and Series.YAxis ("", "left", "right") selects it — see "Dual Y axes" above. XAxis.Labels and YAxis.Labels name the columns and rows of a heatmap; see the heatmap notes below.
  • Format describes how axis labels (and FormatValue) render a float64. Kind selects the family:
    • "" / "number" — plain numeric formatting, Precision decimals.
    • "percent" — multiplies the value by 100 and appends "%".
    • "currency" — prefixes Currency (default "$").
    • "si" — abbreviates magnitude with a k/M/G/T suffix.
    • "time" — treats the value as milliseconds since the Unix epoch and renders it with the Go time layout in Layout (default "2006-01-02"). Note: chart-internal axis values for timeseries charts are seconds-since-epoch, not milliseconds; the timeseries axis formatters convert between the two internally, so FormatValue callers always pass milliseconds.
    • line and scatter charts with a Kind: "time" X-axis Format expect DataPoint.X (or the resolved numeric X) to be milliseconds since the Unix epoch — the same convention FormatValue uses for "time".
  • Data.Series is the ordered list of named series; Data.XAxisData is an optional shared X value list so per-point DataPoint.X can be omitted.
  • DataPoint.Size is accepted in the schema (a scatter point weight) but ignored by every current surface — terminal and ECharts both draw fixed-size markers today.
  • Series.OHLC ([]OHLCPoint) is required by Validate() for ChartTypeOHLC. Build() renders it as time-scaled candlesticks on a *timeserieslinechart.Model (see buildOHLC in build.go and the ChartTypeOHLC notes above); ToECharts() returns *charts.Kline.
  • Heat (*HeatData) holds heatmap data as either a sparse Cells list ({X, Y, Z} triples) or a dense row-major Matrix; MinValue/ MaxValue independently pin the colour-scale domain (data-derived when nil). A nonempty matrix takes precedence over cells; Matrix[y][x] corresponds to a cell at (x, y). Cell indices are whole, non-negative numbers (Build rejects a negative one); each cell is drawn as a filled block, and the blocks tile the plot. Row Y=0 is the first row, drawn at the top, and y_axis.labels[0] names it, as in flint's own heatmaps; x_axis.labels[i] names column X=i, counting from the left. Row labels sit right-aligned in a margin left of the plot, centred on their rows; column labels sit under the plot, each at the left edge of its column. A label that would land on a row already labelled, or run into the previous column label, is left out. The plot grows to cover the labels, so a label with no cells is an empty row or column. With no labels, no margin or label row is reserved and the cells fill the whole chart.
  • Theme.Gradient is an ordered list of "#rrggbb" hex stops interpolated into a colour scale for heatmap rendering; empty falls back to the package's default grayscale scale.

Quick start

import (
    "github.com/NimbleMarkets/ntcharts/v2/barchart"
    "github.com/NimbleMarkets/ntcharts/v2/spec"

    // Web surface only — a separate module, so terminal programs can skip it:
    //   go get github.com/NimbleMarkets/ntcharts/spec/echarts/v2
    "github.com/NimbleMarkets/ntcharts/spec/echarts/v2"
)

s := spec.Spec{
    Type:   spec.ChartTypeBar,
    Title:  "Quarterly Revenue",
    Width:  60,
    Height: 20,
    XAxis: spec.XAxis{
        Type:   spec.XAxisCategory,
        Labels: []string{"Q1", "Q2", "Q3", "Q4"},
    },
    Data: spec.Data{
        Series: []spec.Series{{
            Name:   "Revenue",
            Color:  "#22aadd",
            Values: []spec.DataPoint{{Y: 120}, {Y: 180}, {Y: 95}, {Y: 210}},
        }},
    },
    Options: spec.Options{ShowLegend: true, ShowGrid: true},
}

// Terminal
term, err := spec.Build(s)
if err != nil { /* ... */ }
bc := term.(*barchart.Model)
_ = bc.View()

// Web
web, err := echarts.ToECharts(s)
if err != nil { /* ... */ }
// web is *charts.Bar — call web.Render(w) to produce HTML

Multi-series bar charts must set Options.Stacked = true (see Status above); without it, Build returns an error rather than silently stacking series.

For line, scatter, and heatmap examples see ExampleBuild_line, ExampleBuild_scatter, and ExampleBuild_heatmap in example_test.go. For a time-series example see ExampleBuild_timeSeries. For candlesticks see ExampleBuild_ohlc. For a logarithmic axis see ExampleBuild_logScale.

Time-series specs can also mix line and bar series by setting spec.Series.Type per series. In terminal rendering, bar series are drawn as braille lines just like the other series. In ECharts rendering, Type: "bar" series are overlaid as real bars. Either kind of series goes on the right-hand axis with YAxis: spec.YAxisRight and a Y2Axis (see "Dual Y axes" above). See examples/combo-timeseries-bar for a complete example.

Running the tests

From the repository root:

# Build just this package
go build ./spec/

# Vet + run the runnable examples (ExampleBuild_bar, ExampleBuild_line,
# ExampleBuild_logScale, ExampleBuild_scatter, ExampleBuild_timeSeries,
# ExampleBuild_heatmap, ExampleBuild_ohlc, ExampleBuild_dualAxes)
go vet ./spec/
go test ./spec/

# The web surface is its own module
(cd spec/echarts && go vet ./... && go test ./...)

# Both together
task test-spec

# Verbose, with example output
go test -v ./spec/

# Run a single example
go test -v -run ExampleBuild_bar ./spec/

The examples use // Output: doc-test assertions and therefore verify the concrete Build(s) model type (and, in spec/echarts, the ToECharts() chart type). ExampleBuild_heatmap and ExampleBuild_ohlc show the concrete type and a non-empty view as compact usage examples. Rendering tests inspect heatmap cell colours and candle glyphs directly so ANSI styling does not hide failures.

Dependencies

The spec package itself adds no dependencies to the root module beyond the ntcharts chart packages it builds. The web surface's dependency, github.com/go-echarts/go-echarts/v2, belongs to the nested spec/echarts module only; task check-release fails if it ever leaks into the root module's dependency graph.

Design notes

  • Spec.Validate() catches the obvious mistakes (missing Type, zero dimensions, empty Series, invalid Options.Orientation, Format.Kind, or axis Scale, missing Heat/OHLC data for the chart types that require it). Both Build and ToECharts call it first.
  • Time values in DataPoint.X accept time.Time, RFC 3339 strings, or numeric milliseconds since epoch — see PointTime in helpers.go, which is exported so every surface parses X values identically. Timeseries lines connect points in supplied order; producers should send chronological data. OHLC positions are determined by timestamp; candles sharing a column overdraw in supplied order.
  • Colours prefer Series.Color, fall back to Theme.Palette[i], then the surface default.
  • Terminal sizes are tiny for a browser: ToECharts() scales sub-200 Width/Height by 8×/16× when emitting an Initialization hint, so a 60×20 terminal spec renders as roughly 480×320 px on the web.

Extending

To add a new chart type:

  1. Add the constant to ChartType in spec.go and ChartType.IsKnown().
  2. Add a build<Kind> branch in Build() (build.go).
  3. Add a toECharts<Kind> branch in ToECharts() (echarts/echarts.go).
  4. Add a runnable Example in example_test.go (and echarts/example_test.go).
  5. Update the status table above.

Categorical bar/line combo

The canonical combo uses the existing bar family and per-series overrides; there is no new chart type. It has exactly one left-axis bar series and one right-axis line series, an explicit ordered category list, and y2_axis:

{
  "type": "bar", "width": 60, "height": 16,
  "x_axis": {"type": "category", "labels": ["Jan", "Feb", "Mar"]},
  "y_axis": {"format": {"kind": "currency"}},
  "y2_axis": {"format": {"kind": "percent"}},
  "data": {"series": [
    {"name": "Profit", "type": "bar", "y_axis": "left",
     "values": [{"y": 120}, {"y": -40}, {"y": 180}]},
    {"name": "Margin", "type": "line", "y_axis": "right",
     "values": [{"x": "Jan", "y": 0.12}, {"x": "Mar", "y": 0.18}]}
  ]}
}

Build returns *spec.ComboModel, which embeds the existing linechart.Model for axes, canvas, and View(). Draw() redraws the retained data; Resize(w,h) and Update(tea.WindowSizeMsg) recompute category slots and redraw. Too-small initial dimensions return an error; resizing below the axis margins clears the canvas until it is large enough again. Panning/zooming and editing the embedded model's ranges are not supported: rebuild the spec for new ranges or data. ToECharts returns *charts.Bar with a real line overlay on Y axis index 1.

Category and missing-value rules are shared by both surfaces:

  • XAxis.Labels defines category order. If absent, Data.XAxisData must supply unique string categories. Categories are never alphabetically sorted.
  • A point's explicit string X selects its category. Otherwise shared XAxisData[i] selects it; otherwise the point uses Labels[i].
  • For sparse data, omit the missing point and give every remaining point an explicit X. Trailing positional omissions are also valid. Missing bars draw nothing; missing line values break the line. A singleton draws a dot. Zero is a real value. DataPoint.Y is a float, so JSON null is not a missing-value sentinel; compilers must omit such points instead. NaN and infinity are rejected. The web output uses null slots for omitted values.
  • Duplicate labels, duplicate points within a series/category, unknown categories, and excess positional points return errors.

The left range automatically includes zero and all bar values. Negative bars extend below the zero baseline. Each Y axis resolves its own range, pins, and format; left pins must include zero. Equal or inverted pinned ranges fail. Data outside pinned ranges is clipped. The line is drawn after the bars at the same category centers. Terminal bars use whole cells; dense categories may share cells, and labels are truncated or skipped to avoid overlap. Resize or aggregate upstream when there are more categories than available columns.

Series colors prefer Series.Color, then Theme.Palette in input series order, then blue bars (#63b3ed) and orange lines (#f6ad55). Y labels use the corresponding series colors. Number, currency, percent and SI formats work on both surfaces. Time-valued Y formatting is unsupported by the web combo adapter and returns an error. Terminal titles, legend, background and grid options are not rendered; callers can add their own title/legend around View().

This first scope rejects stacking, horizontal bars, logarithmic scales, extra series, swapped axis assignments, and other series mixtures. Pure single-type charts retain their existing builders. The ECharts adapter retains its existing time-series bar-overlay support; the terminal explicitly rejects those mixed time-series specs instead of silently drawing bars as lines.

Run the self-contained example from the repository root:

go run ./examples/combo-categorical -width 72 -height 18
go run ./examples/combo-categorical -html /tmp/combo.html

For Flint's Combo Chart, the compiler should resolve the category field, bar measure and chartProperties.lineField into this explicit spec. Inferring a second numeric measure and falling back to an ordinary one-series bar spec when none exists belong in flint-ntcharts. Emit explicit X on sparse points, provide unique ordered categories (aggregate duplicate rows upstream), and handle *spec.ComboModel as the terminal result. No custom extension is needed.

Categorical line and scatter axes

Set x_axis.type to "category" to build a *spec.CategoricalModel for a line or scatter spec. It embeds linechart.Model and retains its data for redraws on Resize and WindowSizeMsg. Numeric chart return types are unchanged. Category pan/zoom is disabled; Y axes support existing ranges, formats, and log scales. Categorical X log scales return an error.

{
  "type": "line", "width": 60, "height": 16,
  "x_axis": {"type": "category", "labels": ["Before", "Middle", "After"]},
  "data": {"series": [{"name": "Score", "values": [
    {"x": "Before", "y": 10}, {"x": "After", "y": 30}
  ]}]}
}

XAxis.Labels specifies slot order, including empty categories. If absent, Data.XAxisData supplies ordered string labels; otherwise string point X values are collected in first-appearance order across series. Without a point X, its index selects a declared category (or shared X data). Duplicate labels, unknown categories, nonstring category X, and nonfinite Y values are rejected.

Line points are sorted into category order. Omit a point to represent missing data: its slot remains and the line does not connect across that slot. A line series accepts at most one observation per category; scatter accepts repeated observations. Labels truncate or skip when crowded without shifting marks. The slot and label helpers are shared with the categorical Combo renderer.

Titles, legends, jitter, and point-size rendering are not added by this path. This change is in the terminal builder; the ECharts adapter's line/scatter support remains separate.

Documentation

Overview

Package spec defines a neutral, surface-agnostic chart specification.

A Spec is a declarative description of a chart (type, data, options, theme) that can be rendered to multiple surfaces:

  • ntcharts terminal models via Build()
  • Apache ECharts (go-echarts/v2) web charts via echarts.ToECharts() in the separate github.com/NimbleMarkets/ntcharts/spec/echarts/v2 module, so terminal consumers never pull in go-echarts

The goal is a single source of truth: author once, render anywhere. Specs are JSON-marshalable so they can be persisted, transported over the wire, or authored in configuration files.

Index

Examples

Constants

View Source
const (
	// XAxisCategory indicates a discrete, ordered set of labels
	// (e.g. bar chart categories).
	XAxisCategory = "category"
	// XAxisTime indicates time-valued X coordinates (time.Time or ms-since-epoch).
	XAxisTime = "time"
	// XAxisValue indicates numeric (float64) X coordinates.
	XAxisValue = "value"
)

X-axis type constants used by XAxis.Type.

View Source
const (
	// ScaleLinear spaces values evenly along the axis. It is the default
	// when Scale is empty.
	ScaleLinear = "linear"
	// ScaleLog spaces values by their base-10 logarithm, so each decade
	// takes the same length of axis. Every value on the axis, including a
	// pinned YAxis.Min / YAxis.Max, must be positive.
	ScaleLog = "log"
)

Axis scale constants used by XAxis.Scale and YAxis.Scale.

View Source
const (
	// YAxisLeft is the chart's main Y axis (Spec.YAxis). It is the default
	// when Series.YAxis is empty.
	YAxisLeft = "left"
	// YAxisRight is the optional right-hand Y axis (Spec.Y2Axis).
	YAxisRight = "right"
)

Series.YAxis values: which Y axis a series is plotted against.

View Source
const (
	OrientationVertical   = "vertical"
	OrientationHorizontal = "horizontal"
)

Orientation constants for Options.Orientation.

View Source
const (
	CandleStyleLine  = "line"
	CandleStyleBlock = "block"
)

CandleStyle constants for Options.CandleStyle.

Variables

This section is empty.

Functions

func Build

func Build(s Spec) (any, error)

Build converts a Spec into the appropriate ntcharts terminal model.

The concrete return type depends on Spec.Type:

  • ChartTypeBar -> *barchart.Model (categorical combo: *ComboModel)
  • ChartTypeLine -> *linechart.Model (categorical: *CategoricalModel)
  • ChartTypeTimeSeries -> *timeserieslinechart.Model
  • ChartTypeScatter -> *linechart.Model (categorical: *CategoricalModel)
  • ChartTypeHeatmap -> *heatmap.Model
  • ChartTypeSparkline -> *sparkline.Model
  • ChartTypeOHLC -> *timeserieslinechart.Model (volume: *OHLCModel)

Callers should type-assert the result. Unsupported chart types return an error rather than panicking, so future additions to ChartType do not break existing callers.

A log axis (XAxis.Scale / YAxis.Scale == ScaleLog) sets the model's own scale to linechart.ScaleLog; its ranges stay in data units.

Spec.Y2Axis adds a right-hand Y axis to line, scatter and timeseries charts; series with YAxis == YAxisRight are plotted against it. It obeys the same pin, scale and format rules as YAxis. A categorical bar/line combo also supports Y2Axis; see ResolveCategoricalCombo. Other chart types reject it.

Build does not mutate s.

Example (Bar)

ExampleBuild_bar shows how to describe a bar chart and render it to a terminal via Build. The same Spec renders to the web with echarts.ToECharts from the spec/echarts module.

package main

import (
	"fmt"

	"github.com/NimbleMarkets/ntcharts/v2/barchart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeBar,
		Title:  "Quarterly Revenue",
		Width:  60,
		Height: 20,
		XAxis: spec.XAxis{
			Type:   spec.XAxisCategory,
			Labels: []string{"Q1", "Q2", "Q3", "Q4"},
		},
		Data: spec.Data{
			Series: []spec.Series{{
				Name:  "Revenue",
				Color: "#22aadd",
				Values: []spec.DataPoint{
					{Y: 120}, {Y: 180}, {Y: 95}, {Y: 210},
				},
			}},
		},
		Options: spec.Options{ShowLegend: true, ShowGrid: true},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	_ = term.(*barchart.Model) // *barchart.Model, ready to View()
	fmt.Printf("terminal: %T\n", term)
}
Output:
terminal: *barchart.Model
Example (DualAxes)

ExampleBuild_dualAxes shows a second, right-hand Y axis: load (0..1) on the left and temperature (5..20) on the right share one time axis.

package main

import (
	"fmt"
	"time"

	"github.com/NimbleMarkets/ntcharts/v2/linechart/timeserieslinechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
	load := []float64{0.2, 0.5, 0.4, 0.9, 0.7, 0.3, 0.6}
	temp := []float64{8, 9, 12, 15, 19, 17, 14}
	var l, r []spec.DataPoint
	for i := range load {
		x := start.Add(time.Duration(i) * time.Hour)
		l = append(l, spec.DataPoint{X: x, Y: load[i]})
		r = append(r, spec.DataPoint{X: x, Y: temp[i]})
	}

	s := spec.Spec{
		Type:   spec.ChartTypeTimeSeries,
		Width:  60,
		Height: 12,
		YAxis:  spec.YAxis{Min: f64(0), Max: f64(1)},
		// a second, right-hand Y axis with its own range; series choose it
		// with YAxis: spec.YAxisRight
		Y2Axis: &spec.YAxis{Min: f64(5), Max: f64(20), Title: "Temperature"},
		Data: spec.Data{Series: []spec.Series{
			{Name: "load", Values: l},
			{Name: "temp", YAxis: spec.YAxisRight, Values: r},
		}},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*timeserieslinechart.Model)
	axis, _ := m.Y2Axis()
	fmt.Printf("left %v..%v, right %v..%v\n", m.MinY(), m.MaxY(), axis.Min, axis.Max)
}

func f64(v float64) *float64 { return &v }
Output:
left 0..1, right 5..20
Example (Heatmap)

ExampleBuild_heatmap shows describing a heatmap with a custom gradient color scale (Theme.Gradient) and rendering it via Build to a *heatmap.Model.

This compact example prints model metadata. The rendering tests compare cell background colours directly, independently of terminal colour support.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/heatmap"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeHeatmap,
		Title:  "Correlation Matrix",
		Width:  30,
		Height: 10,
		Heat: &spec.HeatData{
			Cells: []spec.HeatCell{
				{X: 0, Y: 0, Z: 1}, {X: 1, Y: 0, Z: 5}, {X: 2, Y: 0, Z: 9},
				{X: 0, Y: 1, Z: 3}, {X: 1, Y: 1, Z: 7}, {X: 2, Y: 1, Z: 2},
			},
		},
		Theme: spec.Theme{Gradient: []string{"#000044", "#ff4400"}},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*heatmap.Model)
	fmt.Printf("terminal: %T, non-empty view: %v\n", term, strings.TrimSpace(m.View()) != "")
}
Output:
terminal: *heatmap.Model, non-empty view: true
Example (HeatmapLabels)

ExampleBuild_heatmapLabels shows a labelled heatmap. Cells are drawn with background colours, which the Example strips to keep its golden plain: each block of blank cells below is one coloured cell, and the first row label (Mon) is the top row.

package main

import (
	"fmt"
	"strings"

	"github.com/charmbracelet/x/ansi"

	"github.com/NimbleMarkets/ntcharts/v2/heatmap"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	days := []string{"Mon", "Tue", "Wed"}
	hours := []string{"09", "12", "15", "18"}
	var cells []spec.HeatCell
	for y := range days {
		for x := range hours {
			cells = append(cells, spec.HeatCell{X: float64(x), Y: float64(y), Z: float64(x + y*4)})
		}
	}
	s := spec.Spec{
		Type: spec.ChartTypeHeatmap, Width: 28, Height: 9,
		XAxis: spec.XAxis{Labels: hours},
		YAxis: spec.YAxis{Labels: days},
		Heat:  &spec.HeatData{Cells: cells},
		Theme: spec.Theme{Gradient: []string{"#000044", "#ff4400"}},
	}
	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*heatmap.Model)
	for _, line := range strings.Split(ansi.Strip(m.View()), "\n") {
		fmt.Println(strings.TrimRight(line, " ") + "|") // | marks each row's end, so blank rows show
	}
}
Output:
|
Mon|
|
Tue|
|
|
Wed|
    09    12    15    18|
|
Example (Line)

ExampleBuild_line shows describing a numeric-X line chart and rendering it via Build to a *linechart.Model.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/linechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeLine,
		Title:  "Two Series",
		Width:  40,
		Height: 10,
		Data: spec.Data{
			Series: []spec.Series{
				{Name: "a", Values: []spec.DataPoint{
					{X: 0.0, Y: 1}, {X: 1.0, Y: 3}, {X: 2.0, Y: 2}, {X: 3.0, Y: 5},
				}},
				{Name: "b", Values: []spec.DataPoint{
					{X: 0.0, Y: 4}, {X: 1.0, Y: 2}, {X: 2.0, Y: 4}, {X: 3.0, Y: 1},
				}},
			},
		},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*linechart.Model)
	for _, line := range strings.Split(m.View(), "\n") {
		fmt.Println(strings.TrimRight(line, " "))
	}
}
Output:
5│                                   ⢀⠤⠊
 │⢄⡀                      ⣀⢄       ⡠⠒⠁
4│ ⠈⠑⠢⢄⡀              ⣀⠤⠒⠉  ⠉⠢⣀ ⣀⠔⠉
 │     ⠈⠑⠢⢄⣀⡠⠔⠊⠑⠒⠢⣤⣤⣒⠉       ⢀⠤⠛⠤⡀
2│     ⢀⡠⠔⠊⠉⠑⠢⢄⠤⠒⠉   ⠉⠉⠒⠢⠤⢄⡠⠒⠁   ⠈⠒⢄
 │ ⢀⡠⠔⠊⠁                            ⠉⠢⣀
1│⠊⠁                                   ⠑
 │
0└──────────────────────────────────────
 0       1           2           3
Example (LogScale)

ExampleBuild_logScale shows a logarithmic Y axis: YAxis.Scale = ScaleLog gives every decade the same height, so growth from 3 to 1,000,000 stays readable. The unpinned range widens to whole decades (1 to 1M), and with no YAxis.Format the labels use a short k/M suffix. Ticks sit on powers of ten whatever the height: here six decades share eight rows, so every second decade is labelled, on the row where it falls.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/linechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeLine,
		Title:  "Signups",
		Width:  40,
		Height: 10,
		YAxis:  spec.YAxis{Scale: spec.ScaleLog},
		Data: spec.Data{
			Series: []spec.Series{{Name: "signups", Values: []spec.DataPoint{
				{X: 0.0, Y: 3}, {X: 1.0, Y: 40}, {X: 2.0, Y: 150},
				{X: 3.0, Y: 2500}, {X: 4.0, Y: 30000}, {X: 5.0, Y: 1e6},
			}}},
		},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*linechart.Model)
	for _, line := range strings.Split(m.View(), "\n") {
		fmt.Println(strings.TrimRight(line, " "))
	}
}
Output:
 1M│                                ⢀⡠⠔⠊
   │                             ⣀⠤⠒⠁
   │                        ⣀⡠⠔⠒⠉
10k│                   ⣀⠤⠒⠊⠉
   │               ⣀⠤⠒⠉
100│      ⢀⣀⡠⠤⠤⠒⠒⠉⠉
   │  ⣀⠤⠔⠊⠁
   │⠒⠉
  1└────────────────────────────────────
   0   1       2       3     4       5
Example (Ohlc)

ExampleBuild_ohlc shows describing an open/high/low/close chart and rendering it via Build to a *timeserieslinechart.Model. buildOHLC pushes open/high/low/close data sets keyed by each point's parsed time and draws candles at time-scaled X positions across the full graph width via (*timeserieslinechart.Model).DrawCandleWithOpts, with a body width chosen automatically from chart density.

This compact example prints model metadata. The rendering tests inspect candle glyphs with ANSI styling removed.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/linechart/timeserieslinechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeOHLC,
		Title:  "Daily Close",
		Width:  40,
		Height: 12,
		Data: spec.Data{
			Series: []spec.Series{{
				Name: "px",
				OHLC: []spec.OHLCPoint{
					{T: "2026-01-05", O: 100, H: 108, L: 97, C: 105},
					{T: "2026-01-06", O: 105, H: 112, L: 103, C: 110},
					{T: "2026-01-07", O: 110, H: 111, L: 98, C: 99},
					{T: "2026-01-08", O: 99, H: 106, L: 96, C: 104},
				},
			}},
		},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*timeserieslinechart.Model)
	fmt.Printf("terminal: %T, non-empty view: %v\n", term, strings.TrimSpace(m.View()) != "")
}
Output:
terminal: *timeserieslinechart.Model, non-empty view: true
Example (Scatter)

ExampleBuild_scatter shows describing a scatter chart and rendering it via Build to a *linechart.Model; ntcharts has no dedicated scatter model, so points are drawn directly onto a base linechart canvas.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/linechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeScatter,
		Title:  "Fuel Efficiency",
		Width:  40,
		Height: 12,
		Data: spec.Data{
			Series: []spec.Series{
				{Name: "japan", Values: []spec.DataPoint{
					{X: 2100.0, Y: 31.5}, {X: 1980.0, Y: 33.1},
				}},
				{Name: "usa", Values: []spec.DataPoint{
					{X: 2875.0, Y: 24.0}, {X: 3200.0, Y: 19.2}, {X: 3600.0, Y: 16.5},
				}},
			},
		},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*linechart.Model)
	for _, line := range strings.Split(m.View(), "\n") {
		fmt.Println(strings.TrimRight(line, " "))
	}
}
Output:
33│•
  │   •
30│
  │
26│
  │                    •
23│
  │
20│                           •
  │                                    •
16└─────────────────────────────────────
  1980  2243  2505  2768  3031  3294
Example (Sparkline)

ExampleBuild_sparkline shows describing a sparkline chart (single series) and rendering it via Build to a *sparkline.Model. The sparkline is rendered using plain runes with no color styling applied to keep the Example golden escape-free.

package main

import (
	"fmt"
	"strings"

	"github.com/NimbleMarkets/ntcharts/v2/sparkline"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	s := spec.Spec{
		Type:   spec.ChartTypeSparkline,
		Title:  "CPU Usage",
		Width:  30,
		Height: 4,
		Data: spec.Data{
			Series: []spec.Series{{
				Name: "cpu",
				Values: []spec.DataPoint{
					{Y: 1}, {Y: 4}, {Y: 2}, {Y: 7}, {Y: 5}, {Y: 9}, {Y: 3},
				},
			}},
		},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	m := term.(*sparkline.Model)
	for _, line := range strings.Split(m.View(), "\n") {
		fmt.Println(strings.TrimRight(line, " "))
	}
}
Output:
                          ▁ █
                          █▂█
                        ▆ ███▃
                       ▄█▇████
Example (TimeSeries)

ExampleBuild_timeSeries shows describing a time-indexed line chart.

package main

import (
	"fmt"
	"time"

	"github.com/NimbleMarkets/ntcharts/v2/linechart/timeserieslinechart"
	"github.com/NimbleMarkets/ntcharts/v2/spec"
)

func main() {
	start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
	points := make([]spec.DataPoint, 7)
	for i := range points {
		points[i] = spec.DataPoint{
			X: start.Add(time.Duration(i) * 24 * time.Hour),
			Y: float64(10 + i*3),
		}
	}

	s := spec.Spec{
		Type:   spec.ChartTypeTimeSeries,
		Title:  "Daily Active Users",
		Width:  80,
		Height: 24,
		XAxis:  spec.XAxis{Type: spec.XAxisTime},
		Data: spec.Data{
			Series: []spec.Series{{
				Name:   "DAU",
				Values: points,
			}},
		},
		Options: spec.Options{ShowLegend: true},
	}

	term, err := spec.Build(s)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}
	_ = term.(*timeserieslinechart.Model)
	fmt.Printf("terminal: %T\n", term)
}
Output:
terminal: *timeserieslinechart.Model

func ComboSeriesColor added in v2.9.0

func ComboSeriesColor(s Spec, index int) string

ComboSeriesColor returns a series colour, using the palette in input order and distinct defaults when no colour is supplied.

func DeriveBarLabels

func DeriveBarLabels(data Data) []string

DeriveBarLabels returns the category labels for a bar chart whose Spec did not set XAxis.Labels: the first series' DataPoint.X values, falling back to Data.XAxisData for omitted X values, then the 1-based point index where the resolved X is not a string. Every surface that renders bar charts (Build here, ToECharts in the spec/echarts module) applies this same rule so labels agree across them.

func FormatValue

func FormatValue(f Format, v float64) string

FormatValue renders v according to f. Zero-valued fields fall back to per-kind defaults; an empty Kind renders a plain minimal float.

func IsCategoricalCombo added in v2.9.0

func IsCategoricalCombo(s Spec) bool

IsCategoricalCombo reports whether a bar spec requests a series type override. ResolveCategoricalCombo validates that the override is supported.

func PointTime

func PointTime(x any) (time.Time, bool)

PointTime extracts a time.Time from a DataPoint.X value, accepting time.Time, string (RFC 3339), or numeric milliseconds since epoch. The boolean result reports whether a time was successfully extracted.

func PointX

func PointX(p DataPoint, index int, shared []any) any

PointX returns p.X, falling back to shared[index] when p.X is nil. If index is outside shared, an omitted X remains nil. Neither p nor shared is modified.

Types

type CategoricalCombo added in v2.9.0

type CategoricalCombo struct {
	Labels               []string
	Bars, Line           []*float64
	BarIndex, LineIndex  int
	Min, Max, Min2, Max2 float64
}

CategoricalCombo is the resolved, shared input for terminal and web renderers. Values are indexed by Labels; nil means missing, not zero. Series indexes refer to the original spec, preserving palette order even if line comes first.

func ResolveCategoricalCombo added in v2.9.0

func ResolveCategoricalCombo(s Spec) (CategoricalCombo, error)

ResolveCategoricalCombo accepts a parent bar chart with exactly one left bar and one right line, a Y2Axis, and linear categorical axes. Labels are required explicitly (XAxis.Labels or Data.XAxisData); sparse points name their category. It does not mutate s. Callers should Validate s first.

type CategoricalModel added in v2.9.0

type CategoricalModel struct {
	linechart.Model
	// contains filtered or unexported fields
}

CategoricalModel renders line or scatter data on ordered category slots. The embedded linechart supplies Y scales and formatting. Missing categories retain their slots and break lines. Numeric pan/zoom is disabled.

func (*CategoricalModel) Draw added in v2.9.0

func (m *CategoricalModel) Draw()

Draw recomputes slot centers from the current plot width. Declared empty categories consume space; dense labels are truncated or skipped, never moved.

func (*CategoricalModel) Resize added in v2.9.0

func (m *CategoricalModel) Resize(w, h int)

Resize redraws category slots and labels without discarding the data.

func (CategoricalModel) Update added in v2.9.0

func (m CategoricalModel) Update(msg tea.Msg) (CategoricalModel, tea.Cmd)

Update accepts window sizes without allowing numeric category-axis pan/zoom.

type ChartType

type ChartType string

ChartType identifies the kind of chart described by a Spec. The constants below mirror the chart families exposed by ntcharts.

const (
	// ChartTypeBar renders a bar chart (barchart package).
	ChartTypeBar ChartType = "bar"
	// ChartTypeLine renders a generic (numeric-X) line chart (linechart package).
	ChartTypeLine ChartType = "line"
	// ChartTypeTimeSeries renders a time-indexed line chart
	// (linechart/timeserieslinechart package).
	ChartTypeTimeSeries ChartType = "timeseries"
	// ChartTypeStreamline renders a streamline chart
	// (linechart/streamlinechart package).
	ChartTypeStreamline ChartType = "streamline"
	// ChartTypeSparkline renders a sparkline (sparkline package).
	ChartTypeSparkline ChartType = "sparkline"
	// ChartTypeHeatmap renders a heatmap (heatmap package).
	ChartTypeHeatmap ChartType = "heatmap"
	// ChartTypeOHLC renders an open/high/low/close financial chart.
	ChartTypeOHLC ChartType = "ohlc"
	// ChartTypeScatter renders a scatter plot.
	ChartTypeScatter ChartType = "scatter"
	// ChartTypeCanvas renders a raw canvas chart (canvas package).
	ChartTypeCanvas ChartType = "canvas"
)

ChartType constants. These mirror the ntcharts chart families. Build renders every type except Streamline and Canvas, which are reserved for future support; the web surface (spec/echarts) implements Bar, OHLC and TimeSeries. See spec/README.md for the per-type status table.

func (ChartType) IsKnown

func (t ChartType) IsKnown() bool

IsKnown reports whether the ChartType is one of the recognized constants.

type ComboModel added in v2.9.0

type ComboModel struct {
	linechart.Model
	// contains filtered or unexported fields
}

ComboModel renders a resolved categorical bar/line combo. The embedded linechart supplies axes, formatting, canvas and View. Draw and Resize retain the resolved data. Panning/zooming are not supported.

func (*ComboModel) Draw added in v2.9.0

func (m *ComboModel) Draw()

Draw paints bars first, then the line, using the same integer category centers. Missing values keep their slots; a missing line value breaks the connection.

func (*ComboModel) Resize added in v2.9.0

func (m *ComboModel) Resize(w, h int)

Resize recomputes category slots and redraws. Windows too small for the axes have an empty canvas and recover when resized larger.

func (ComboModel) Update added in v2.9.0

func (m ComboModel) Update(msg tea.Msg) (ComboModel, tea.Cmd)

Update handles window resizing without enabling numeric-axis pan/zoom.

type Data

type Data struct {
	// Series is the ordered collection of data series. At least one series is
	// required for most chart types.
	Series []Series `json:"series"`
	// XAxisData is an optional shared X-axis value list (time.Time, float64,
	// string, or int). If provided, per-series DataPoint.X may be omitted and
	// points are zipped against this slice. An explicit DataPoint.X takes
	// precedence. Used by bar, line, scatter, and timeseries charts.
	XAxisData []any `json:"x_axis_data,omitempty"`
}

Data describes the series of a chart.

type DataPoint

type DataPoint struct {
	// X is the independent-axis coordinate.
	X any `json:"x,omitempty"`
	// Y is the dependent-axis value.
	Y float64 `json:"y"`
	// Size is an optional scatter point weight. Surfaces that do not support
	// variable point sizing may ignore it.
	Size *float64 `json:"size,omitempty"`
}

DataPoint is a single datum in a Series.

X may be a string (category), time.Time (time series), float64 or int (numeric value). When unmarshaled from JSON, time values are represented as RFC 3339 strings and resolved by helpers in this package when needed.

type Format

type Format struct {
	// Kind selects the formatting family. See the Format doc comment.
	Kind string `json:"kind,omitempty"`
	// Precision is the number of decimals. nil means the kind's default.
	Precision *int `json:"precision,omitempty"`
	// Currency is the symbol used for kind "currency". Defaults to "$".
	Currency string `json:"currency,omitempty"`
	// Layout is the Go time layout string used for kind "time".
	Layout string `json:"layout,omitempty"`
}

Format describes how numeric or time values render as labels.

Kind is one of:

  • "" or "number": plain numeric formatting
  • "percent": v*100 followed by a "%" suffix
  • "currency": Currency symbol prefix
  • "si": k/M/G/T suffix (SI-style magnitude abbreviation)
  • "time": ms-since-epoch rendered via Layout

Note: chart-internal axis values for timeseries charts are seconds-since-epoch (not milliseconds); FormatValue and the timeseries axis formatters convert between the two internally, so callers of FormatValue always pass milliseconds regardless of which surface renders the chart.

func (Format) IsZero

func (f Format) IsZero() bool

IsZero reports whether f is the zero value (no formatting directive set).

type HeatCell

type HeatCell struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
	Z float64 `json:"z"`
}

HeatCell is a single (x, y, z) datum in a HeatData.Cells list.

type HeatData

type HeatData struct {
	// Cells is a sparse list of (x, y, z) cells.
	Cells []HeatCell `json:"cells,omitempty"`
	// Matrix is a row-major dense alternative to Cells: Matrix[y][x].
	// A nonempty Matrix takes precedence over Cells.
	Matrix [][]float64 `json:"matrix,omitempty"`
	// MinValue pins the colour-scale domain minimum. If nil, auto.
	MinValue *float64 `json:"min_value,omitempty"`
	// MaxValue pins the colour-scale domain maximum. If nil, auto.
	MaxValue *float64 `json:"max_value,omitempty"`
}

HeatData holds heatmap cell/matrix data, used by ChartTypeHeatmap.

type OHLCModel added in v2.9.0

type OHLCModel struct {
	canvas.Model
	// contains filtered or unexported fields
}

OHLCModel is a candlestick chart with a volume panel sharing its time scale, candle widths, colours and Y-axis gutter. The bottom quarter is reserved for volume; X labels appear only below that panel. Resize and Draw retain the spec data. Panning and zooming are not supported.

func (*OHLCModel) Draw added in v2.9.0

func (m *OHLCModel) Draw()

Draw redraws the retained spec at the current canvas dimensions.

func (*OHLCModel) Resize added in v2.9.0

func (m *OHLCModel) Resize(w, h int)

Resize redraws both panels. Undersized windows are blank and recover on resize.

func (OHLCModel) Update added in v2.9.0

func (m OHLCModel) Update(msg tea.Msg) (OHLCModel, tea.Cmd)

Update handles window resizing without enabling independent panel pan/zoom.

type OHLCPoint

type OHLCPoint struct {
	// T is the point's time: time.Time, RFC3339 string, or ms-since-epoch.
	T any `json:"t"`
	// O is the opening value.
	O float64 `json:"o"`
	// H is the high value.
	H float64 `json:"h"`
	// L is the low value.
	L float64 `json:"l"`
	// C is the closing value.
	C float64 `json:"c"`
	// V is optional non-negative volume. Nil means missing; zero is a known zero.
	V *float64 `json:"v,omitempty"`
}

OHLCPoint is a single open/high/low/close datum, used by ChartTypeOHLC.

type Options

type Options struct {
	// Volume shows an OHLC volume panel below price when any point has V set.
	// It is supported only for ChartTypeOHLC; missing volumes leave gaps.
	Volume bool `json:"volume,omitempty"`
	// ShowLegend toggles the legend.
	ShowLegend bool `json:"show_legend,omitempty"`
	// ShowGrid toggles the background grid.
	ShowGrid bool `json:"show_grid,omitempty"`
	// Orientation controls bar chart orientation: "" or OrientationVertical
	// for vertical bars, OrientationHorizontal for horizontal bars.
	Orientation string `json:"orientation,omitempty"`
	// Stacked stacks bar chart series instead of grouping them.
	Stacked bool `json:"stacked,omitempty"`
	// CandleStyle selects the OHLC candle rendering style: "" or
	// CandleStyleLine for box-drawing line runes, CandleStyleBlock for
	// solid block bodies. Unknown values are a Build error.
	CandleStyle string `json:"candle_style,omitempty"`
}

Options are common, surface-agnostic rendering options.

Surfaces are free to ignore options they do not support.

type Series

type Series struct {
	// Name is the series name (shown in legends and tooltips). Required.
	Name string `json:"name"`
	// Type optionally overrides the parent Spec.Type for this series
	// (e.g. mixing "line" into a "bar" chart). Build supports one left bar
	// and one right line on a categorical bar spec; see ResolveCategoricalCombo.
	// Unsupported mixtures return errors rather than substituting marks.
	Type string `json:"type,omitempty"`
	// Values is the ordered list of points in the series.
	Values []DataPoint `json:"values"`
	// OHLC is the ordered list of open/high/low/close points in the series,
	// used by ChartTypeOHLC. Build renders them as candlesticks.
	OHLC []OHLCPoint `json:"ohlc,omitempty"`
	// Color is an optional per-series colour (hex, "#rrggbb", or a named
	// colour). If empty, the Theme palette or surface default is used.
	Color string `json:"color,omitempty"`
	// YAxis selects the Y axis the series is plotted against: "" or
	// YAxisLeft for the main axis, or YAxisRight for the right-hand axis,
	// which requires Spec.Y2Axis.
	YAxis string `json:"y_axis,omitempty"`
}

Series is a named collection of DataPoints.

type Spec

type Spec struct {
	// Type selects the chart family. Required.
	Type ChartType `json:"type"`
	// Title is the optional main chart title.
	Title string `json:"title,omitempty"`
	// Subtitle is an optional secondary title.
	Subtitle string `json:"subtitle,omitempty"`
	// Width is the suggested width of the chart. For terminal surfaces this
	// is columns; for web surfaces this is a pixel hint.
	Width int `json:"width"`
	// Height is the suggested height. Columns/rows on terminal, pixels on web.
	Height int `json:"height"`

	// XAxis describes the X axis (title, type, labels, format).
	XAxis XAxis `json:"x_axis,omitzero"`
	// YAxis describes the Y axis (title, min/max, format).
	YAxis YAxis `json:"y_axis,omitzero"`
	// Y2Axis describes the optional right-hand Y axis. Series select it
	// with Series.YAxis = YAxisRight. Build supports it on line, scatter
	// and timeseries charts, and categorical bar/line combos. Its fields
	// match YAxis
	// (Labels is ignored). Nil means the chart has one Y axis.
	Y2Axis *YAxis `json:"y2_axis,omitempty"`

	// Data holds the series data for the chart.
	Data Data `json:"data"`
	// Heat holds heatmap cell/matrix data. Required (non-nil, non-empty) for
	// ChartTypeHeatmap.
	Heat *HeatData `json:"heat,omitempty"`
	// Options holds common, surface-agnostic rendering options.
	Options Options `json:"options,omitzero"`
	// Theme holds surface-agnostic colour theming.
	Theme Theme `json:"theme,omitzero"`
}

Spec is the top-level neutral description of a chart.

A Spec fully describes the chart. Surface-specific concerns (styles, interactivity, mouse/keyboard handling) are derived from Spec by the corresponding renderer.

func (Spec) HasVolume added in v2.9.0

func (s Spec) HasVolume() bool

HasVolume reports whether the OHLC volume panel is enabled and has data.

func (Spec) MarshalJSON

func (s Spec) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler so that Spec values round-trip cleanly even when DataPoint.X carries a time.Time.

func (Spec) Validate

func (s Spec) Validate() error

Validate reports the first structural error in the Spec, if any.

Validate is intentionally lightweight: it catches the obvious mistakes (missing type, zero dimensions, empty series, a right-hand series without y2_axis) without prejudging what the target surface considers renderable.

type Theme

type Theme struct {
	// Background is a hex or named background colour for the chart area.
	Background string `json:"background,omitempty"`
	// Foreground is the default colour for axes, labels and text.
	Foreground string `json:"foreground,omitempty"`
	// Palette is an ordered list of colours used for series that do not
	// supply their own Color.
	Palette []string `json:"palette,omitempty"`
	// Gradient is an ordered list of hex stops ("#rrggbb") used for
	// sequential colormaps (heatmap).
	Gradient []string `json:"gradient,omitempty"`
}

Theme describes surface-agnostic colours. Individual surfaces map these to their native style systems (lipgloss on terminal, CSS colours on web).

type XAxis

type XAxis struct {
	// Title is the optional axis title.
	Title string `json:"title,omitempty"`
	// Type declares the kind of X axis: XAxisCategory, XAxisTime, or
	// XAxisValue. If empty, a sensible default is inferred from the chart type.
	Type string `json:"type,omitempty"`
	// Labels is the optional list of category labels, used when
	// Type == XAxisCategory. Line/scatter charts preserve these ordered slots;
	// an omitted line point breaks the connection across that slot. If Labels
	// is absent, category order comes from XAxisData or string X values.
	// For a heatmap, Labels[i] names the column of
	// cells at X = i and is drawn under the plot.
	Labels []string `json:"labels,omitempty"`
	// Format describes how axis labels render.
	Format Format `json:"format,omitzero"`
	// Scale is "" or ScaleLinear for a linear axis, or ScaleLog for a
	// base-10 logarithmic one. Build honours ScaleLog for line and scatter
	// charts (numeric X); it is a Build error on every other chart type,
	// and for any X value <= 0. Unknown values fail Validate.
	Scale string `json:"scale,omitempty"`
}

XAxis describes the X axis of a chart.

type YAxis

type YAxis struct {
	// Title is the optional axis title.
	Title string `json:"title,omitempty"`
	// Min pins the Y axis minimum. If nil, auto-scale.
	Min *float64 `json:"min,omitempty"`
	// Max pins the Y axis maximum. If nil, auto-scale.
	Max *float64 `json:"max,omitempty"`
	// Labels is the optional list of row labels for grid-style charts. For a
	// heatmap, Labels[i] names the row of cells at Y = i; row 0 is drawn at
	// the top, and the labels are drawn left of the plot. Other chart types
	// ignore it.
	Labels []string `json:"labels,omitempty"`
	// Format describes how axis labels render.
	Format Format `json:"format,omitzero"`
	// Scale is "" or ScaleLinear for a linear axis, or ScaleLog for a
	// base-10 logarithmic one. Build honours ScaleLog for line, scatter,
	// timeseries, and OHLC charts; it is a Build error on bar, heatmap, and
	// sparkline charts, and for any Y value or Min / Max pin <= 0. An
	// unpinned bound widens to a whole decade; Min and Max stay in data
	// units. Unknown values fail Validate.
	Scale string `json:"scale,omitempty"`
}

YAxis describes the Y axis of a chart.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL