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 ¶
- Constants
- func Build(s Spec) (any, error)
- func ComboSeriesColor(s Spec, index int) string
- func DeriveBarLabels(data Data) []string
- func FormatValue(f Format, v float64) string
- func IsCategoricalCombo(s Spec) bool
- func PointTime(x any) (time.Time, bool)
- func PointX(p DataPoint, index int, shared []any) any
- type CategoricalCombo
- type CategoricalModel
- type ChartType
- type ComboModel
- type Data
- type DataPoint
- type Format
- type HeatCell
- type HeatData
- type OHLCModel
- type OHLCPoint
- type Options
- type Series
- type Spec
- type Theme
- type XAxis
- type YAxis
Examples ¶
Constants ¶
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.
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.
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.
const ( OrientationVertical = "vertical" OrientationHorizontal = "horizontal" )
Orientation constants for Options.Orientation.
const ( CandleStyleLine = "line" CandleStyleBlock = "block" )
CandleStyle constants for Options.CandleStyle.
Variables ¶
This section is empty.
Functions ¶
func Build ¶
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
ComboSeriesColor returns a series colour, using the palette in input order and distinct defaults when no colour is supplied.
func DeriveBarLabels ¶
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 ¶
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
IsCategoricalCombo reports whether a bar spec requests a series type override. ResolveCategoricalCombo validates that the override is supported.
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
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.
type ComboModel ¶ added in v2.9.0
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.
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
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.
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
HasVolume reports whether the OHLC volume panel is enabled and has data.
func (Spec) MarshalJSON ¶
MarshalJSON implements json.Marshaler so that Spec values round-trip cleanly even when DataPoint.X carries a time.Time.
func (Spec) Validate ¶
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.