ggplot

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: MIT Imports: 26 Imported by: 0

README

ggplot

Go Reference Go Report Card CI codecov GitHub release (latest by date)

ggplot

Production-grade Grammar of Graphics for Go.

A pure-Go data visualization library implementing a rigorous, declarative Grammar of Graphics pipeline. Inspired by Hadley Wickham's renowned ggplot2, but architected specifically for Go's type safety and interface-driven engine architecture.

Overview

ggplot provides an expressive, composable API for generating complex data visualizations. It decouples data manipulation (Apache Arrow, BigQuery, Memory) from statistical transformations and final rendering, resulting in highly scalable plotting pipelines.

Capability Supported Features
Geometries Point, Line, Step, Bar, Col, Histogram, Area, Density, Polygon, Rug, HLine, VLine, Segment, Text, BoxPlot, Smooth, Tile, ErrorBar, Crossbar, Linerange, Pointrange, Curve, Violin, Dotplot, Raster, JitterPoint
Statistics Identity, Bin/Count, Density (KDE), Smooth (LOESS + lm), Summary, BoxPlot (Tukey/range whiskers, notch CI), ViolinY (grouped KDE), DotBin (Wilkinson stacking)
Aesthetics Size, Alpha, Shape, Linetype — per-point and per-group mapping
Scales Linear, Log10, Sqrt, Reverse, Discrete, DateTime, Binned, Size, Alpha, Shape, Linetype, Identity
Color Palettes 60+ built-in palettes — Viridis, ColorBrewer, Tab10, Observable, Seaborn, and more
Faceting Grid (row ~ col, margins, drop), Wrap (NCols, drop), Labellers (Value, Both, Context, custom)
Data Backends Native Memory, Apache Arrow IPC/Parquet, BigQuery SQL pushdown
Data Types Float64, Int64, String, Bool, Timestamp, Date, Time
Output PNG, SVG 1.1, PDF 1.4, HiDPI via WithScale()
Theming 60+ themes — Dashboard, Dark, Classic, Minimal, Observable, Seaborn, Nord, Dracula, and more
Annotations AnnotateText, AnnotateRect, AnnotateSegment, AnnotateArrow, AnnotateLabel — layer-less fixed-coordinate annotations
Coordinate Systems CoordCartesian (viewport zoom), CoordFixed (aspect ratio), CoordFlip, Coord(Polar())

What's New in v0.0.9

Advanced Faceting

Free scales, grid margins, custom labellers, and strip placement:

ggplot.New(ds, aes.X("x"), aes.Y("y")).
    Layer(geom.Point()).
    FacetWrap("species", facet.FreeY()).   // independent Y range per panel
    Save(ctx, "facets.png", 900, 300)

ggplot.New(ds, aes.X("x"), aes.Y("y")).
    Layer(geom.Point()).
    FacetGrid("year", "site", facet.GridMargins(true)).  // row/col/corner "All" panels
    Save(ctx, "grid.png", 900, 600)

Labellers (facet.LabelValue, LabelBoth, LabelContext, Label(fn)), facet.Drop(false) to keep empty panels, facet.GridSpace("free_y") for proportional sizing, and facet.StripBottom() / GridStripLeft() for strip repositioning.

Secondary Axes

Dual Y-axis derived from the primary via a transform pair, or a mirrored duplicate:

ggplot.New(ds, aes.X("hour"), aes.Y("temp_c")).
    Layer(geom.Point(geom.WithColor("steelblue"))).
    SecondAxis(scale.SecAxis(
        func(c float64) float64 { return c*9/5 + 32 },       // °C → °F
        func(f float64) float64 { return (f - 32) * 5 / 9 }, // °F → °C
        "Temperature (°F)",
    )).
    Save(ctx, "dual_axis.png", 800, 500)

// scale.DupAxis("°C") mirrors the primary axis on the right.
Theme Overrides

Per-plot element overrides without authoring a custom theme:

ggplot.New(ds, aes.X("x"), aes.Y("y")).
    Layer(geom.Point()).
    Theme("default").
    ThemeOverride(
        theme.StripTextOverride(theme.ElementText{Bold: true, Size: 13}),
    ).
    Save(ctx, "styled.png", 800, 500)
New Geometries & Coordinate Systems

geom.Violin, geom.Dotplot, geom.Raster, geom.Curve, geom.Crossbar, geom.Linerange, geom.Pointrange, and geom.JitterPoint. Coordinate systems: CoordCartesian (viewport zoom), CoordFixed (aspect ratio), CoordFlip, and Coord(coord.Polar(...)). Coordinate transforms now dispatch to engine-native math kernels (Arrow compute / SQL functions) instead of scalar fallbacks.

⚠️ Breaking Changes
  • Plot.FacetWrap(col string, opts ...WrapOpt) — was (col, nCols, nRows). Use facet.NCols(n).
  • Plot.FacetGrid(row, col string, opts ...GridOpt) — replaces the old two-arg form.
  • Plot.SecondaryYPlot.SecondAxis.
  • coord.TransFunc is now a name-only spec type (math moved to engine MathKernel).
What was new in v0.0.8
Aesthetics Mapping

Map data columns directly to visual properties — size, transparency, shape, and line style:

ggplot.New(ds, aes.X("x"), aes.Y("y"), aes.Size("magnitude"), aes.Alpha("confidence")).
    Layer(geom.Point()).
    ScaleSizeArea().              // area-proportional sizing
    ScaleAlpha(0.2, 0.9).        // opacity range
    Save(ctx, "scatter.png", 800, 500)
Shape & Linetype Scales

Categorical columns map to distinct shapes or dash patterns:

ggplot.New(ds, aes.X("x"), aes.Y("y"), aes.Shape("species")).
    Layer(geom.Point(geom.WithSize(5))).
    Save(ctx, "shapes.png", 800, 500)

ggplot.New(ds, aes.X("date"), aes.Y("value"), aes.Linetype("model")).
    Layer(geom.Line()).
    Save(ctx, "linetypes.png", 800, 500)

10 built-in shapes: circle, square, triangle, diamond, triangleDown, plus, cross, star, pentagon, hexagon. 6 built-in linetypes: solid, dashed, dotted, dotdash, longdash, twodash.

Shape Constants

All shape names are now exported constants (canvas.ShapeCircle, canvas.ShapeStar, etc.) — no more magic strings.

What was new in v0.0.7
  • CIELAB gradient constructors: colormap.Gradient(), Gradient2(), GradientN() with perceptually uniform interpolation
  • Theme-aware colour defaults: Separate Color/Fill palettes per theme
  • Legend key glyphs: Circle for points, line for smooth, rectangle for bars
  • Guide customization: ColorBarWidth(), ColorBarNBin(), LegendCols()
  • NA color: scale.SetNAColor() for missing value display
What was new in v0.0.6
  • Temporal data types: DTypeTimestamp, DTypeDate, DTypeTime across all engines
  • DateTime scale: scale.DateTime with auto calendar-aligned ticks
  • Binned scale: scale.Binned with WithBins(n) and WithBinBreaks(edges)
  • Out-of-bounds policies: scale.WithOOB(OOBSquish | OOBCensor)
  • Opt-in drivers: GPU, CSV, Parquet as blank-import packages

Full changelog: CHANGELOG.md


Clifford Attractor Butterfly Curve
Clifford attractor — 500k points, alpha blending, continuous color scale Butterfly curve — parametric path with color interpolation
Geometries
Point Line Step
geom.Point geom.Line geom.Step
Bar Col Histogram
geom.Bar geom.Col geom.Histogram
Area Density Smooth
geom.Area geom.Density geom.Smooth
Boxplot ErrorBar Rug
geom.Boxplot geom.ErrorBar geom.Rug
Text Segment
geom.Text geom.HLine / geom.VLine geom.Segment
Polygon Tile Crossbar
geom.Polygon geom.Tile geom.Crossbar
Linerange Pointrange Curve
geom.Linerange geom.Pointrange geom.Curve
Violin Dotplot Raster
geom.Violin geom.Dotplot geom.Raster
JitterPoint
geom.JitterPoint
Annotations
Annotations
Plot.Annotate() — text, rect, segment, arrow, label
Coordinate Systems
CoordFixed CoordZoom
CoordFixed(1) — circle stays circular CoordCartesian — viewport zoom
Faceting & Advanced Axes
Shared Scales Free Y
FacetWrap("species") — shared scales FacetWrap("species", FreeY()) — independent Y per panel
Secondary Axis Dup Axis
SecondAxis(SecAxis(°C→°F)) — dual Y-axis SecondAxis(DupAxis("°C")) — mirrored axis

Each image is generated by a self-contained example in examples/.


Quick Start

Installation
go get github.com/TuSKan/ggplot
Scatter Plot with Smooth
package main

import (
	"context"
	"log"

	"github.com/TuSKan/ggplot"
	"github.com/TuSKan/ggplot/aes"
	"github.com/TuSKan/ggplot/dataset"
	"github.com/TuSKan/ggplot/dataset/memory"
	"github.com/TuSKan/ggplot/geom"
)

func main() {
	ctx := context.Background()
	eng := memory.NewEngine(ctx)
	ds, err := dataset.NewDataset(eng,
		eng.NewFloat64Column("x", []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}),
		eng.NewFloat64Column("y", []float64{2, 4, 5, 4, 6, 8, 7, 9, 10, 11}),
	)
	if err != nil {
		log.Fatalln(err)
	}

	ggplot.New(ds, aes.X("x"), aes.Y("y")).
		Layer(geom.Point(geom.WithSize(5), geom.WithColor("coral"))).
		Layer(geom.Smooth()).
		Labs(ggplot.Title("Quick Start"), ggplot.XLab("X"), ggplot.YLab("Y")).
		Save(ctx, "scatter.png", 800, 500)
}
Faceted Time Series
ggplot.New(ds, aes.X("day"), aes.Y("temp")).
    Layer(geom.Line(geom.WithColor("seagreen"), geom.WithLineWidth(1.5))).
    FacetWrap("season", facet.NCols(2)).
    Labs(ggplot.Title("Temperature by Season")).
    Theme("dark").
    Save(ctx, "facets.png", 900, 600)
Box Plot with Groups
ggplot.New(ds, aes.X("group"), aes.Y("value")).
    Layer(geom.Boxplot(geom.WithFill("#E8E8E8"), geom.WithAlpha(0.8))).
    Labs(ggplot.Title("Distribution by Group")).
    Theme("classic").
    Save(ctx, "boxplot.png", 800, 500)

Why ggplot?

  • Declarative composition — Build complex charts by layering geometries and statistics instead of drawing pixels.
  • Provider-agnostic engines — Swap out the dataset engine (memoryarrowbigquery) without changing plotting code.
  • Publication-ready output — Anti-aliased 2D rendering powered by gogpu/gg, saving to PNG, SVG, or PDF at configurable DPI scales.
  • 60+ built-in themes — From minimal dashboards to editorial typography to neon cyberpunk.
  • Parallel rendering — Panel-parallel build and draw pipelines via errgroup for multi-facet plots.

Architecture & Data Backends

ggplot is built around an interface-driven dataset.Table engine. You are not limited to []float64 slices — back your plots with robust columnar frameworks. See DATASET.md for a deep-dive.

  • Memory Engine (dataset/memory) — Lightweight native Go slices. Best for standard web-server rendering.
  • Arrow Engine (dataset/arrow) — Apache Arrow backed IPC streams and Parquet datasets. Zero-copy reads. Best for datasets >1M rows.
  • BigQuery Engine (dataset/bigquery) — Lazy SQL pushdown execution. Best for massive data warehouses where filtering and aggregation execute on the database before streaming visual aggregates to Go.

Theming

ggplot ships 60+ built-in themes. Use .Theme("name") to switch:

p.Theme("dashboard")   // clean card-style (default)
p.Theme("dark")        // dark background
p.Theme("minimal")     // minimal chrome
p.Theme("observable")  // Observable-inspired
p.Theme("nord")        // Nord palette
p.Theme("cyberpunk")   // neon-on-dark

See all themes with theme.AllNames().


Documentation

Document Description
DATASET.md Deep dive into the Engine abstraction, Memory, and Arrow backends
ARCHITECTURE.md Package map, rendering pipeline, design decisions
ROADMAP.md Development plan aligned with the ggplot2 book (3e)
BENCHMARK.md Arrow vs Memory engine performance benchmarks

Dependencies

Package Role
gogpu/gg 2D vector rendering with anti-aliased lines, fills, and text
apache/arrow-go Columnar data (zero-copy for IPC/Parquet reads)

Contributing

Contributions are welcome!

License

MIT — see LICENSE.

Documentation

Overview

Package ggplot is a production-grade, pure-Go Grammar of Graphics plotting library.

Inspired by R's ggplot2, it provides a declarative, composable API for building statistical visualizations from data, aesthetics, geometries, scales, coordinate systems, facets, and themes.

Quick Start

p := ggplot.New(ds,
    aes.X("x"),
    aes.Y("y"),
    aes.Color("group"),
).
    Layer(geom.Point(geom.WithSize(4), geom.WithAlpha(0.7))).
    Layer(geom.Smooth()).
    Labs(ggplot.Title("My Plot"), ggplot.XLab("X Axis")).
    Theme("minimal").
    Save("output.png", 1200, 800)

Architecture

The library follows a strict pipeline:

PlotSpec -> Validate -> Stat Transform -> Scale Training -> Layout -> Render

All data flows through the dataset.Dataset abstraction. Multiple engine backends are supported: memory (Go slices), Apache Arrow (columnar arrays), and BigQuery (SQL pushdown). Arrow IPC and Parquet ingest provide zero-copy reads; constructing from Go slices requires one copy.

Index

Constants

View Source
const (
	ColPANEL = "PANEL" // int64 -- facet panel index (0-based)
	ColGroup = "group" // int64 -- group index within a panel (0-based)
)

System column names reserved by the build pipeline. These columns are injected into every layer's dataset during Build.

Variables

View Source
var (
	// ErrUnsupportedFormat is returned for unsupported output formats.
	ErrUnsupportedFormat = errors.New("ggplot: unsupported output format")

	// ErrRenderFailed is returned when rendering fails.
	ErrRenderFailed = errors.New("ggplot: render failed")

	// ErrNoLayers is returned when there are no layers to render.
	ErrNoLayers = errors.New("ggplot: no layers to render")

	// ErrMissingAesthetic is returned when a required aesthetic is missing.
	ErrMissingAesthetic = errors.New("ggplot: missing required aesthetic")

	// ErrInvalidConfig is returned for invalid plot configuration.
	ErrInvalidConfig = errors.New("ggplot: invalid configuration")

	// ErrUnsupportedTransform is returned for unknown coord transform names.
	ErrUnsupportedTransform = errors.New("ggplot: unsupported coordinate transform")
)

Sentinel errors for the ggplot package.

Functions

func RegisterDrawer

func RegisterDrawer(t geom.Type, d Drawer)

RegisterDrawer registers a Drawer for a geometry type. Replaces any previously registered drawer for the same type. Third-party geom types should call this at init() time.

Types

type AesMap added in v0.0.4

type AesMap map[string]string

AesMap maps aesthetic channel names to column names.

func ToAesMap added in v0.0.4

func ToAesMap(mappings []aes.Mapping) AesMap

ToAesMap converts a slice of aes.Mapping into an AesMap.

func (AesMap) Merge added in v0.0.4

func (a AesMap) Merge(other AesMap) AesMap

Merge returns a new AesMap with entries from other as base, overridden by entries from the receiver (a takes priority).

type Annotation added in v0.0.9

type Annotation struct {
	Type AnnotationType

	// Data-space coordinates.
	// For text/label: (X, Y) is the anchor point.
	// For rect: (X, Y) is xmin/ymin and (XEnd, YEnd) is xmax/ymax.
	// For segment/arrow: (X, Y) to (XEnd, YEnd).
	X, Y       float64
	XEnd, YEnd float64

	// Text content for text and label annotations.
	Label string

	// Visual parameters. Reuses geom.Params so that all existing
	// WithColor, WithFill, WithAlpha, etc. options work unchanged.
	Params geom.Params
}

Annotation is a fixed-coordinate visual element that bypasses the data/stat/position pipeline entirely. Annotations are drawn in data space after all data layers so they appear on top. They do not participate in scale training — if their coordinates fall outside the data domain they are clipped (consistent with geom.HLine / geom.VLine behaviour).

func AnnotateArrow added in v0.0.9

func AnnotateArrow(x, y, xend, yend float64, opts ...geom.Opt) Annotation

AnnotateArrow creates a line segment with an arrowhead at the endpoint, from (x, y) to (xend, yend) in data coordinates.

Example:

p.Annotate(ggplot.AnnotateArrow(1, 5, 4, 8,
    geom.WithColor("#333333"), geom.WithLineWidth(1.5)))

func AnnotateLabel added in v0.0.9

func AnnotateLabel(x, y float64, label string, opts ...geom.Opt) Annotation

AnnotateLabel creates a text annotation with a filled background box at data coordinates (x, y). The box padding is controlled by geom.WithPadding (default 4px).

Example:

p.Annotate(ggplot.AnnotateLabel(3.14, 1.0, "outlier",
    geom.WithFill("#FFFFFF"), geom.WithColor("#333333"),
    geom.WithAlpha(0.9)))

func AnnotateRect added in v0.0.9

func AnnotateRect(xmin, ymin, xmax, ymax float64, opts ...geom.Opt) Annotation

AnnotateRect creates a filled rectangle annotation spanning from (xmin, ymin) to (xmax, ymax) in data coordinates.

Example:

p.Annotate(ggplot.AnnotateRect(1.0, 0, 3.0, 10,
    geom.WithFill("#FFCCCC"), geom.WithAlpha(0.3)))

func AnnotateSegment added in v0.0.9

func AnnotateSegment(x, y, xend, yend float64, opts ...geom.Opt) Annotation

AnnotateSegment creates a line segment annotation from (x, y) to (xend, yend) in data coordinates.

Example:

p.Annotate(ggplot.AnnotateSegment(1, 5, 4, 8,
    geom.WithColor("#333333"), geom.WithLineWidth(1.5)))

func AnnotateText added in v0.0.9

func AnnotateText(x, y float64, label string, opts ...geom.Opt) Annotation

AnnotateText creates a text annotation at data coordinates (x, y).

Example:

p.Annotate(ggplot.AnnotateText(3.14, 1.0, "peak",
    geom.WithColor("#E74C3C"), geom.WithFontSize(12)))

type AnnotationType added in v0.0.9

type AnnotationType string

AnnotationType identifies the kind of annotation.

const (
	AnnotationText    AnnotationType = "text"    // text label at (X, Y)
	AnnotationRect    AnnotationType = "rect"    // filled rectangle from (X, Y) to (XEnd, YEnd)
	AnnotationSegment AnnotationType = "segment" // line from (X, Y) to (XEnd, YEnd)
	AnnotationArrow   AnnotationType = "arrow"   // line with arrowhead from (X, Y) to (XEnd, YEnd)
	AnnotationLabel   AnnotationType = "label"   // text with background box at (X, Y)
)

Supported annotation types.

type AxisGuide added in v0.0.9

type AxisGuide struct {
	NDodge int
}

AxisGuide controls axis label layout — dodging, overlap handling, and rotation for dense categorical axes.

NDodge sets the number of stagger rows for axis tick labels. When NDodge is 0, the renderer auto-detects overlapping labels and staggers them across 2 rows. Set NDodge to 1 to disable dodging. Values ≥ 2 force that many stagger rows.

type Built added in v0.0.4

type Built struct {
	// contains filtered or unexported fields
}

Built is the result of Plot.Build. It holds fully resolved layer data, trained scales, layout geometry, and theme — everything needed to draw without re-running the grammar pipeline.

This is the Go equivalent of ggplot2's ggplot_build(plot) → built.

func (*Built) Draw added in v0.0.4

func (b *Built) Draw(ctx context.Context, cv canvas.Canvas, width, height int) error

Draw renders the built plot onto the given canvas at the specified dimensions.

This is the Go equivalent of ggplot2's grid.draw(ggplot_gtable(built)).

func (*Built) DrawCanvas added in v0.0.4

func (b *Built) DrawCanvas(ctx context.Context, width, height int) (*canvas.GGCanvas, error)

DrawCanvas creates a new canvas.GGCanvas and draws the built plot onto it. The caller owns the returned canvas and must call canvas.GGCanvas.Close when finished to release GPU resources.

func (*Built) Explain added in v0.0.5

func (b *Built) Explain() string

Explain returns a human-readable summary of the built plot's structure, including panels, layers, transform pipelines, and output hints.

func (*Built) Labels added in v0.0.4

func (b *Built) Labels() Labels

Labels returns the resolved plot labels.

func (*Built) LayerData added in v0.0.4

func (b *Built) LayerData(panel, layer int) dataset.Dataset

LayerData returns the resolved dataset for the given layer in the given panel. This is the data each geom actually sees after stat/position transforms — the primary introspection API for debugging and platform-independent testing.

func (*Built) NumLayers added in v0.0.4

func (b *Built) NumLayers(panel int) int

NumLayers returns the number of resolved layers in the given panel.

func (*Built) NumPanels added in v0.0.4

func (b *Built) NumPanels() int

NumPanels returns the number of facet panels.

func (*Built) PanelLayout added in v0.0.4

func (b *Built) PanelLayout() Layout

PanelLayout returns the layout geometry.

func (*Built) PipelineFor added in v0.0.5

func (b *Built) PipelineFor(panel, layer int) []string

PipelineFor returns the ordered transform names for the given panel and layer. Panel and layer indices are zero-based.

func (*Built) Save added in v0.0.4

func (b *Built) Save(ctx context.Context, filename string, width, height int, opts ...RenderOpt) error

Save renders the built plot to a file. Format is inferred from extension. If height ≤ 0, it is inferred from width and the y-scale type:

  • continuous y: width / φ (golden ratio ≈ 1.618)
  • discrete y: 18px per category, clamped to [240, width]

Supported extensions:

.png — raster PNG (default)
.svg — SVG 1.1 vector
.pdf — PDF 1.4 vector

Options: WithScale for HiDPI output.

func (*Built) Theme added in v0.0.4

func (b *Built) Theme() theme.Theme

Theme returns the resolved theme.

func (*Built) WriteTo added in v0.0.4

func (b *Built) WriteTo(ctx context.Context, w io.Writer, format string, width, height int, opts ...RenderOpt) (int64, error)

WriteTo writes the built plot to w in the given format. Supported formats: "png" (default), "svg", "pdf". If height ≤ 0, it is inferred from width (see Built.Save for rules). Options: WithScale for HiDPI output. Returns the number of bytes written.

type BuiltLayer added in v0.0.4

type BuiltLayer struct {
	Geom          geom.Layer
	Data          dataset.Dataset
	Mapping       AesMap
	ContColorCol  string
	ContColScale  *colormap.Scale
	SizeCol       string
	SizeScale     scale.Scale
	AlphaCol      string
	AlphaScale    scale.Scale
	ShapeCol      string
	ShapeScale    scale.Scale
	LinetypeCol   string
	LinetypeScale scale.Scale
}

BuiltLayer holds one resolved layer's data after stat transform and grouping. The Data dataset always contains the system column PANEL (int64). When the layer was produced by group splitting, the system column group (int64) is also present.

type BuiltPanel added in v0.0.4

type BuiltPanel struct {
	Label         string
	Layers        []BuiltLayer
	XScale        scale.Scale
	YScale        scale.Scale
	LegendEntries []LegendEntry
	LegendTitle   string
	ColorBarSpec  *ColorBarSpec
	XIsDiscrete   bool
}

BuiltPanel holds one facet panel with its resolved layers and trained scales.

type ColorBarSpec added in v0.0.4

type ColorBarSpec struct {
	Title    string
	Cmap     colormap.Cmap
	Norm     colormap.Norm
	BarWidth float64 // 0 = default (12px)
	NBin     int     // 0 = default (pixel-matched strips)
}

ColorBarSpec describes a continuous color bar legend.

Cmap and Norm replace the previous opaque ColorFunc field: the bar walks Cmap.At directly across the [0,1] range, and Norm provides the data-space labels at the endpoints (and any future intermediate ticks).

type DrawContext

type DrawContext struct {
	Canvas        canvas.Canvas
	Coord         coord.Coord
	Data          dataset.Dataset
	Mapping       AesMap
	Params        geom.Params
	Theme         theme.Theme     // active theme for default styling
	ContColorCol  string          // continuous color column (empty if none)
	ContScale     *colormap.Scale // continuous color scale (nil if none)
	W, H          float64         // panel size in pixels
	XMin, XMax    float64         // data domain bounds
	YMin, YMax    float64         // data domain bounds
	SizeCol       string
	SizeScale     scale.Scale
	AlphaCol      string
	AlphaScale    scale.Scale
	ShapeCol      string
	ShapeScale    scale.Scale
	LinetypeCol   string
	LinetypeScale scale.Scale
}

DrawContext holds the rendering parameters passed to a Drawer. It encapsulates the canvas, coordinate system, data, aesthetic mappings, and panel bounds so that Drawer implementations are self-contained.

type Drawer

type Drawer interface {
	Draw(ctx DrawContext)
}

Drawer renders a geometry type onto the canvas. Implementations are registered via RegisterDrawer and looked up by geom.Type during rendering.

func LookupDrawer

func LookupDrawer(t geom.Type) Drawer

LookupDrawer returns the registered Drawer for the given type, or nil.

type DrawerFunc

type DrawerFunc func(DrawContext)

DrawerFunc is an adapter to allow use of ordinary functions as [Drawer]s.

func (DrawerFunc) Draw

func (f DrawerFunc) Draw(ctx DrawContext)

Draw calls f(ctx).

type Error added in v0.0.6

type Error struct {
	Phase Phase  // pipeline phase (Build, Draw, Render)
	Layer int    // 0-based layer index, -1 if not layer-specific
	Stage string // sub-stage within the phase (e.g. "transform", "scale", "facet")
	Msg   string // short human-readable description
	Cause error  // underlying error (may be nil)
}

Error is a structured error from the ggplot pipeline. It supports errors.Is (via Cause chain) and errors.As.

Usage:

var ggErr *ggplot.Error
if errors.As(err, &ggErr) {
    fmt.Printf("phase=%s layer=%d stage=%s\n", ggErr.Phase, ggErr.Layer, ggErr.Stage)
}

func Errorf added in v0.0.6

func Errorf(phase Phase, layer int, stage string, cause error, msg string, args ...any) *Error

Errorf creates a structured *Error. Layer should be -1 if the error is not layer-specific.

func (*Error) Error added in v0.0.6

func (e *Error) Error() string

Error returns a formatted error string.

Examples:

"ggplot [build/facet]: facet split"
"ggplot [build/layer 2/transform]: transform pipeline failed for group \"A\""
"ggplot [render]: unsupported format \"gif\""

func (*Error) Unwrap added in v0.0.6

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for errors.Is / errors.As traversal.

type LabOpt

type LabOpt func(*Labels)

LabOpt is a functional option for configuring plot labels.

func Caption

func Caption(text string) LabOpt

Caption sets the plot caption.

func Subtitle

func Subtitle(text string) LabOpt

Subtitle sets the plot subtitle.

func Title

func Title(text string) LabOpt

Title sets the plot title.

func XLab

func XLab(text string) LabOpt

XLab sets the x-axis label.

func YLab

func YLab(text string) LabOpt

YLab sets the y-axis label.

type Labels added in v0.0.4

type Labels struct {
	Title    string
	Subtitle string
	X        string
	Y        string
	Caption  string
}

Labels holds all text annotations for a plot.

type LayerSpec added in v0.0.4

type LayerSpec struct {
	Geom    geom.Layer
	Mapping AesMap // per-layer aesthetic overrides
}

LayerSpec describes a single visual layer in the plot.

type Layout added in v0.0.4

type Layout struct {
	Rows   int
	Cols   int
	Panels []PanelLayout
	FreeX  bool // per-panel independent X scales
	FreeY  bool // per-panel independent Y scales
}

Layout holds the panel grid dimensions derived from faceting.

type LegendEntry added in v0.0.4

type LegendEntry struct {
	Label    string
	Color    gg.RGBA
	Glyph    LegendGlyph
	Shape    string    // e.g. "square", "triangle"
	Linetype []float64 // dash pattern
}

LegendEntry describes one item in the legend.

type LegendGlyph added in v0.0.7

type LegendGlyph int

LegendGlyph controls the key shape drawn beside each legend entry.

const (
	// GlyphRect draws a filled square swatch (bars, histogram, tile, area).
	GlyphRect LegendGlyph = iota
	// GlyphPoint draws a filled circle (point, rug).
	GlyphPoint
	// GlyphLine draws a horizontal line stroke (line, smooth, step, segment).
	GlyphLine
)

type LegendPos

type LegendPos string

LegendPos controls legend placement.

const (
	LegendRight  LegendPos = "right"
	LegendLeft   LegendPos = "left"
	LegendTop    LegendPos = "top"
	LegendBottom LegendPos = "bottom"
	LegendNone   LegendPos = "none"
)

LegendRight places the legend to the right of the plot.

type PanelLayout added in v0.0.4

type PanelLayout struct {
	Row    int
	Col    int
	RowVal string // raw row facet value (Grid only, "" for Wrap/None)
	ColVal string // raw column facet value (Grid only, "" for Wrap/None)
	XScale scale.Scale
	YScale scale.Scale
}

PanelLayout holds per-panel geometry and trained scale state.

type Phase added in v0.0.6

type Phase int

Phase identifies the pipeline phase where an error occurred.

const (
	// PhaseBuild is the Plot.Build phase (data → stat → scale → position).
	PhaseBuild Phase = iota
	// PhaseDraw is the Built.Draw phase (rendering to canvas).
	PhaseDraw
	// PhaseRender is the Save/WriteTo phase (format dispatch, I/O).
	PhaseRender
)

func (Phase) String added in v0.0.6

func (p Phase) String() string

String returns a human-readable phase name.

type Plot

type Plot struct {
	// contains filtered or unexported fields
}

Plot is the immutable, declarative plot builder. Every method returns a new Plot with the modification applied, enabling a fluent chaining style.

Plot is safe to share and reuse - modifying a derived plot does not affect the original.

func New

func New(ds dataset.Dataset, globalAes ...aes.Mapping) *Plot

New initializes a plot with a dataset and optional global aesthetic mappings.

func (*Plot) Aes

func (p *Plot) Aes(mappings ...aes.Mapping) *Plot

Aes adds or overrides global aesthetic mappings.

func (*Plot) Annotate added in v0.0.9

func (p *Plot) Annotate(a Annotation) *Plot

Annotate adds a fixed-coordinate annotation to the plot. Annotations bypass the data/stat/position pipeline and are drawn after all data layers. They do not affect scale training.

See AnnotateText, AnnotateRect, AnnotateSegment, AnnotateArrow, and AnnotateLabel for constructors.

func (*Plot) AxisLabelRows added in v0.0.9

func (p *Plot) AxisLabelRows(n int) *Plot

AxisLabelRows controls the X-axis label layout. N sets the number of stagger rows for tick labels. When n is 0 (default), overlapping labels are automatically detected and staggered across 2 rows. Set n to 1 to disable staggering. Values ≥ 2 force that many rows.

func (*Plot) Build added in v0.0.4

func (p *Plot) Build(ctx context.Context) (*Built, error)

Build resolves the plot specification through the grammar pipeline and returns a *Built containing fully resolved layer data, trained scales, layout geometry, and theme. The result can be inspected via Built.LayerData or rendered via Built.Draw.

This is the Go equivalent of ggplot2's ggplot_build(plot).

func (*Plot) ColorBarNBin added in v0.0.7

func (p *Plot) ColorBarNBin(n int) *Plot

ColorBarNBin sets the number of discrete gradient steps in the color bar. Zero resets to default (256).

func (*Plot) ColorBarWidth added in v0.0.7

func (p *Plot) ColorBarWidth(w float64) *Plot

ColorBarWidth sets the width of the continuous color bar in pixels. Zero resets to default (12px).

func (*Plot) Coord

func (p *Plot) Coord(c coord.Coord) *Plot

Coord sets the coordinate system.

func (*Plot) CoordCartesian added in v0.0.9

func (p *Plot) CoordCartesian(xmin, xmax, ymin, ymax float64) *Plot

CoordCartesian sets a Cartesian viewport zoom. Unlike Plot.XLim/Plot.YLim which set scale bounds early (potentially affecting stat computations), CoordCartesian overrides bounds after scale training — all data participates in stat computations, only the visible window changes.

Pass math.NaN() for any endpoint to auto-detect from training.

func (*Plot) CoordFixed added in v0.0.9

func (p *Plot) CoordFixed(ratio float64) *Plot

CoordFixed sets a Cartesian coordinate system with a fixed aspect ratio. ratio is defined as (pixels per data-unit-y) / (pixels per data-unit-x). ratio = 1 gives equal scaling — one unit of x occupies the same pixel length as one unit of y.

func (*Plot) CoordFlip

func (p *Plot) CoordFlip() *Plot

CoordFlip swaps the x and y axes. This is sugar for setting geom.Horizontal orientation on all layers and swapping the axis labels.

func (*Plot) CoordTrans added in v0.0.9

func (p *Plot) CoordTrans(xtrans, ytrans coord.TransFunc) *Plot

CoordTrans sets a Cartesian coordinate system with per-axis mathematical transforms applied post-stat. Unlike scale transforms (e.g., scale.Log10) which transform data before stat computations, CoordTrans transforms the display without affecting statistics.

func (*Plot) FacetGrid

func (p *Plot) FacetGrid(rowCol, colCol string, opts ...facet.GridOpt) *Plot

FacetGrid applies grid faceting by row and column variables.

func (*Plot) FacetWrap

func (p *Plot) FacetWrap(col string, opts ...facet.WrapOpt) *Plot

FacetWrap applies wrap faceting by a column.

func (*Plot) Labs

func (p *Plot) Labs(opts ...LabOpt) *Plot

Labs configures plot labels (title, subtitle, axis labels, caption).

func (*Plot) Layer

func (p *Plot) Layer(l geom.Layer, localAes ...aes.Mapping) *Plot

Layer adds a geometry layer to the plot with optional per-layer aesthetic overrides.

func (*Plot) LegendCols added in v0.0.7

func (p *Plot) LegendCols(n int) *Plot

LegendCols sets the number of columns for the categorical legend. Zero resets to single column (vertical) or single row (horizontal).

func (*Plot) LegendPosition

func (p *Plot) LegendPosition(pos LegendPos) *Plot

LegendPosition sets the legend placement.

func (*Plot) Save

func (p *Plot) Save(ctx context.Context, filename string, width, height int, opts ...RenderOpt) error

Save renders the plot to a file at the given dimensions. If height ≤ 0, it is inferred from width (see Built.Save for rules). The output format is inferred from the file extension:

.png — raster PNG (default)
.svg — SVG 1.1 vector
.pdf — PDF 1.4 vector

Options: WithScale for HiDPI output.

func (*Plot) ScaleAlpha added in v0.0.8

func (p *Plot) ScaleAlpha(rangeMin, rangeMax float64) *Plot

ScaleAlpha configures an opacity scale mapping to the specified range.

func (*Plot) ScaleAlphaIdentity added in v0.0.8

func (p *Plot) ScaleAlphaIdentity() *Plot

ScaleAlphaIdentity configures an identity scale for alpha, passing values through.

func (*Plot) ScaleColor

func (p *Plot) ScaleColor(c colormap.Cmap) *Plot

ScaleColor configures the color aesthetic to use the given colormap. The cmap is composed with a default LinearNorm for continuous data, or used as a Listed palette for discrete data. Pass nil to clear an existing override and fall back to defaults.

func (*Plot) ScaleColorContinuous

func (p *Plot) ScaleColorContinuous(c colormap.Cmap, n colormap.Norm) *Plot

ScaleColorContinuous installs an explicit continuous color scale composed of the given Cmap and Norm. Use this to control LogNorm / TwoSlopeNorm / PowerNorm / data-range limits beyond the simple Plot.ScaleColor form.

func (*Plot) ScaleColorManual

func (p *Plot) ScaleColorManual(m map[string]colormap.Color) *Plot

ScaleColorManual maps category labels to specific colors. Categories not in m fall back to the default Tab10 palette in the order they are encountered during dataset training.

func (*Plot) ScaleFill

func (p *Plot) ScaleFill(c colormap.Cmap) *Plot

ScaleFill is the fill-aesthetic counterpart of Plot.ScaleColor.

func (*Plot) ScaleLinetype added in v0.0.8

func (p *Plot) ScaleLinetype() *Plot

ScaleLinetype configures a categorical linetype scale with automatic dash pattern assignment.

func (*Plot) ScaleLinetypeManual added in v0.0.8

func (p *Plot) ScaleLinetypeManual(m map[string]string) *Plot

ScaleLinetypeManual configures a categorical linetype scale with a manual mapping.

func (*Plot) ScaleShape added in v0.0.8

func (p *Plot) ScaleShape() *Plot

ScaleShape configures a categorical shape scale with automatic shape assignment.

func (*Plot) ScaleShapeManual added in v0.0.8

func (p *Plot) ScaleShapeManual(m map[string]string) *Plot

ScaleShapeManual configures a categorical shape scale with a manual mapping.

func (*Plot) ScaleSize added in v0.0.8

func (p *Plot) ScaleSize(rangeMin, rangeMax float64) *Plot

ScaleSize configures a size scale mapping to the specified point-radius range.

func (*Plot) ScaleSizeArea added in v0.0.8

func (p *Plot) ScaleSizeArea() *Plot

ScaleSizeArea configures a size scale mapping values proportionally to point area.

func (*Plot) ScaleSizeIdentity added in v0.0.8

func (p *Plot) ScaleSizeIdentity() *Plot

ScaleSizeIdentity configures an identity scale for size, passing values through.

func (*Plot) ScaleX

func (p *Plot) ScaleX(scaleType scale.Type, opts ...scale.Opt) *Plot

ScaleX sets the x-axis scale type with optional configuration. Options: scale.WithBreaks, scale.WithLabels, scale.WithFormatter, scale.WithExpand, scale.WithMinorBreaks, scale.WithClipBounds.

func (*Plot) ScaleY

func (p *Plot) ScaleY(scaleType scale.Type, opts ...scale.Opt) *Plot

ScaleY sets the y-axis scale type with optional configuration. Options: scale.WithBreaks, scale.WithLabels, scale.WithFormatter, scale.WithExpand, scale.WithMinorBreaks, scale.WithClipBounds.

func (*Plot) SecondAxis added in v0.0.9

func (p *Plot) SecondAxis(spec scale.SecAxisSpec) *Plot

SecondAxis adds a secondary Y-axis derived from the primary Y-axis via a transform pair. The secondary axis is rendered on the right side of the plot with its own tick labels and optional axis title.

Example — show Fahrenheit alongside Celsius:

p.SecondAxis(scale.SecAxis(
    func(c float64) float64 { return c*9/5 + 32 },
    func(f float64) float64 { return (f - 32) * 5 / 9 },
    "Temperature (°F)",
))

func (*Plot) Theme

func (p *Plot) Theme(name theme.Name) *Plot

Theme sets the visual theme.

func (*Plot) ThemeOverride added in v0.0.9

func (p *Plot) ThemeOverride(overrides ...theme.Override) *Plot

ThemeOverride applies per-plot theme element overrides. These are applied after the base theme is resolved, allowing fine-grained control over individual elements without creating a custom theme.

Example — bold X-axis title:

p.ThemeOverride(theme.AxisTitleXOverride(theme.ElementText{Bold: true}))

func (*Plot) WriteTo

func (p *Plot) WriteTo(ctx context.Context, w io.Writer, format string, width, height int, opts ...RenderOpt) (int64, error)

WriteTo renders the plot and writes the output to w in the given format. Supported formats: "png" (default), "svg", "pdf". If height ≤ 0, it is inferred from width (see Built.Save for rules). Options: WithScale for HiDPI output. Returns the number of bytes written.

Shorthand for Plot.Build followed by Built.WriteTo.

func (*Plot) XLim

func (p *Plot) XLim(lo, hi float64) *Plot

XLim sets explicit x-axis limits. Pass math.NaN() for either end to auto-detect.

func (*Plot) YLim

func (p *Plot) YLim(lo, hi float64) *Plot

YLim sets explicit y-axis limits. Pass math.NaN() for either end to auto-detect.

type PlotSpec added in v0.0.4

type PlotSpec struct {
	// Dataset is the primary data source.
	Dataset dataset.Dataset

	// GlobalMapping maps aesthetic channels to column names at the plot level.
	// Per-layer mappings override these.
	GlobalMapping AesMap

	// Layers describes each visual layer (geom + stat + position + local aes).
	Layers []LayerSpec

	// ScaleOverrides holds user-specified scale configurations, keyed by
	// aesthetic channel ("x", "y", "color", etc.).
	ScaleOverrides map[string]ScaleOverride

	// ColorScales holds user-specified color/fill scales, keyed by
	// aesthetic channel ("color" or "fill"). nil entries fall back to
	// the auto-detected default ([colormap.Viridis] for continuous data,
	// [colormap.Tab10] for discrete data).
	ColorScales map[string]*colormap.Scale

	// Coord defines the coordinate system (default: Cartesian).
	Coord coord.Coord

	// Facet defines the faceting strategy (default: None).
	Facet facet.Facet

	// Theme holds the theme name or configuration.
	ThemeName theme.Name

	// Labels holds plot title, subtitle, axis labels, caption.
	Labels Labels

	// XLim and YLim hold optional user-specified axis limits.
	// nil means auto-detect from data.
	XLim [2]*float64
	YLim [2]*float64

	// LegendPosition controls where the legend is drawn.
	LegendPosition string

	// AxisGuideX controls X-axis label layout (dodging, overlap handling).
	AxisGuideX AxisGuide

	// ColorBarWidth sets the width of the continuous color bar in pixels.
	// Zero means default (12px).
	ColorBarWidth float64
	// ColorBarNBin sets the number of discrete gradient steps in the color bar.
	// Zero means default (256).
	ColorBarNBin int
	// LegendNCols sets the number of columns for the categorical legend.
	// Zero means single column (vertical) or single row (horizontal).
	LegendNCols int

	// Mapped scale overrides configured via Plot builder methods.
	SizeScale     scale.Scale
	AlphaScale    scale.Scale
	ShapeScale    scale.Scale
	LinetypeScale scale.Scale

	// Annotations holds fixed-coordinate visual elements that bypass the
	// data/stat/position pipeline. They are drawn after all data layers.
	Annotations []Annotation

	// SecondAxis holds a secondary Y-axis specification. When non-nil,
	// a right-side Y-axis is drawn with ticks derived from the primary Y
	// through the transform function pair.
	SecondAxis *scale.SecAxisSpec

	// ThemeOverrides holds per-plot theme element overrides.
	// Applied after the base theme is resolved, before rendering.
	ThemeOverrides []theme.Override
}

PlotSpec is the fully declarative specification of a plot, produced by the user-facing builder API and consumed by the compilation pipeline.

type RenderOpt

type RenderOpt func(*renderConfig)

RenderOpt configures rendering output (scale, DPI, etc.).

func WithCPU added in v0.0.5

func WithCPU() RenderOpt

WithCPU forces pure-CPU analytic rasterization, bypassing the GPU accelerator. This produces deterministic output across multiple renders in a single process and is useful for golden/snapshot tests.

func WithScale

func WithScale(s float64) RenderOpt

WithScale sets the DPI scale factor for rendering. scale=2.0 produces retina-resolution output (2× pixel density).

type ScaleOverride added in v0.0.4

type ScaleOverride struct {
	Type   scale.Type        // e.g., scale.Log10, scale.Sqrt, scale.Reverse
	Params map[string]string // type-specific parameters
	Opts   []scale.Opt       // functional options (WithBreaks, WithLabels, etc.)
}

ScaleOverride captures a user-requested scale for a specific aesthetic channel.

Directories

Path Synopsis
Package aes provides aesthetic mapping constructors for the Grammar of Graphics.
Package aes provides aesthetic mapping constructors for the Grammar of Graphics.
Package canvas defines the rendering backend abstraction.
Package canvas defines the rendering backend abstraction.
gpu
Package gpu opts in GPU acceleration.
Package gpu opts in GPU acceleration.
Package colormap provides a matplotlib-style colormap and color-scale API for the ggplot grammar of graphics pipeline.
Package colormap provides a matplotlib-style colormap and color-scale API for the ggplot grammar of graphics pipeline.
Package coord defines coordinate systems that control how data positions are mapped to the 2D plotting surface.
Package coord defines coordinate systems that control how data positions are mapped to the 2D plotting surface.
Package dataset provides columnar data abstractions for the Grammar of Graphics pipeline.
Package dataset provides columnar data abstractions for the Grammar of Graphics pipeline.
arrow
Package arrow provides an Apache Arrow-backed compute engine for the dataset package.
Package arrow provides an Apache Arrow-backed compute engine for the dataset package.
arrow/csv
Package csv provides the Arrow CSV engine driver.
Package csv provides the Arrow CSV engine driver.
arrow/parquet
Package parquet provides the Arrow Parquet engine driver.
Package parquet provides the Arrow Parquet engine driver.
bigquery
Package bigquery implements a BigQuery SQL pushdown engine for the dataset library.
Package bigquery implements a BigQuery SQL pushdown engine for the dataset library.
compute
Package compute provides portable SIMD primitives for the dataset engines.
Package compute provides portable SIMD primitives for the dataset engines.
csv
Package csv provides CSV reading and writing for the dataset package.
Package csv provides CSV reading and writing for the dataset package.
math
Package math provides SIMD-accelerated mathematical transforms for the dataset engines.
Package math provides SIMD-accelerated mathematical transforms for the dataset engines.
memory
Package memory provides a lightweight Go-slice-backed compute engine for the dataset package.
Package memory provides a lightweight Go-slice-backed compute engine for the dataset package.
memory/csv
Package csv provides the Memory CSV engine driver.
Package csv provides the Memory CSV engine driver.
memory/parquet
Package parquet provides the Memory Parquet engine driver.
Package parquet provides the Memory Parquet engine driver.
parquet
Package parquet provides Parquet reading and writing for the dataset package.
Package parquet provides Parquet reading and writing for the dataset package.
sort
Package sort provides SIMD-accelerated sorting for the dataset engines.
Package sort provides SIMD-accelerated sorting for the dataset engines.
examples
annotations command
Example: Reference lines and text annotations.
Example: Reference lines and text annotations.
annotations/annotate command
Example annotate demonstrates the annotation API — layer-less visual elements at fixed data coordinates.
Example annotate demonstrates the annotation API — layer-less visual elements at fixed data coordinates.
axis_label_rows command
Example axis_label_rows demonstrates the AxisLabelRows feature for dense categorical X-axis labels.
Example axis_label_rows demonstrates the AxisLabelRows feature for dense categorical X-axis labels.
butterfly command
Example: Butterfly curve with continuous color gradient.
Example: Butterfly curve with continuous color gradient.
categorical command
Example: Boxplot and Categorical (Discrete) X Axis
Example: Boxplot and Categorical (Discrete) X Axis
clifford command
Example: (Clifford[https://paulbourke.net/fractals/clifford/] attractor with continuous color gradient.
Example: (Clifford[https://paulbourke.net/fractals/clifford/] attractor with continuous color gradient.
color_mapping command
Example: Multi-Group Scatter with Colour Mapping and Legend
Example: Multi-Group Scatter with Colour Mapping and Legend
coord_cartesian_zoom command
Example coord_cartesian_zoom demonstrates viewport zoom without data clipping.
Example coord_cartesian_zoom demonstrates viewport zoom without data clipping.
coord_fixed command
Example coord_fixed demonstrates fixed aspect ratio — 1:1 equal scaling so that one unit of x occupies the same pixel length as one unit of y.
Example coord_fixed demonstrates fixed aspect ratio — 1:1 equal scaling so that one unit of x occupies the same pixel length as one unit of y.
coord_flip command
Example: Orientation — every geometry flipped to horizontal.
Example: Orientation — every geometry flipped to horizontal.
coord_trans command
Example coord_trans demonstrates post-stat axis transforms.
Example coord_trans demonstrates post-stat axis transforms.
facet_free_scales command
Example: Facet Free Scales.
Example: Facet Free Scales.
facet_labeller command
Example: Facet Labellers, Drop, and Grid Margins.
Example: Facet Labellers, Drop, and Grid Margins.
geometries/area command
Example area demonstrates the geom.area geometry.
Example area demonstrates the geom.area geometry.
geometries/bar command
Example bar demonstrates the geom.bar geometry.
Example bar demonstrates the geom.bar geometry.
geometries/boxplot command
Example boxplot demonstrates the geom.Boxplot geometry.
Example boxplot demonstrates the geom.Boxplot geometry.
geometries/col command
Example col demonstrates the geom.Col geometry (pre-computed bar chart).
Example col demonstrates the geom.Col geometry (pre-computed bar chart).
geometries/crossbar command
Example crossbar demonstrates the geom.Crossbar geometry for showing a filled box between ymin/ymax with a median line at y.
Example crossbar demonstrates the geom.Crossbar geometry for showing a filled box between ymin/ymax with a median line at y.
geometries/curve command
Example curve demonstrates the geom.Curve geometry for drawing quadratic bezier curves between pairs of endpoints.
Example curve demonstrates the geom.Curve geometry for drawing quadratic bezier curves between pairs of endpoints.
geometries/density command
Example density demonstrates the geom.Density geometry.
Example density demonstrates the geom.Density geometry.
geometries/dotplot command
Example dotplot demonstrates the geom.Dotplot geometry for showing individual observations as stacked dots within bins.
Example dotplot demonstrates the geom.Dotplot geometry for showing individual observations as stacked dots within bins.
geometries/errorbar command
Example errorbar demonstrates the geom.ErrorBar geometry for showing measurement uncertainty with vertical bars and caps.
Example errorbar demonstrates the geom.ErrorBar geometry for showing measurement uncertainty with vertical bars and caps.
geometries/histogram command
Example histogram demonstrates the geom.histogram geometry.
Example histogram demonstrates the geom.histogram geometry.
geometries/hline_vline command
Example hline_vline demonstrates the geom.HLine and geom.VLine geometries.
Example hline_vline demonstrates the geom.HLine and geom.VLine geometries.
geometries/jitter_point command
Example jitter_point demonstrates geom.JitterPoint — a scatter plot with random displacement to reduce overplotting.
Example jitter_point demonstrates geom.JitterPoint — a scatter plot with random displacement to reduce overplotting.
geometries/line command
Example line demonstrates the geom.line geometry.
Example line demonstrates the geom.line geometry.
geometries/linerange command
Example linerange demonstrates the geom.Linerange geometry for showing vertical lines from ymin to ymax without caps — a minimal range indicator.
Example linerange demonstrates the geom.Linerange geometry for showing vertical lines from ymin to ymax without caps — a minimal range indicator.
geometries/point command
Example point demonstrates the geom.point geometry.
Example point demonstrates the geom.point geometry.
geometries/pointrange command
Example pointrange demonstrates the geom.Pointrange geometry for showing a point at the central estimate with a vertical line spanning the range.
Example pointrange demonstrates the geom.Pointrange geometry for showing a point at the central estimate with a vertical line spanning the range.
geometries/polygon command
Example polygon demonstrates the geom.Polygon geometry for drawing closed filled shapes from grouped x/y coordinates.
Example polygon demonstrates the geom.Polygon geometry for drawing closed filled shapes from grouped x/y coordinates.
geometries/raster command
Example raster demonstrates the geom.Raster dense pixel-aligned image grid.
Example raster demonstrates the geom.Raster dense pixel-aligned image grid.
geometries/rug command
Example rug demonstrates the geom.Rug geometry.
Example rug demonstrates the geom.Rug geometry.
geometries/segment command
Example segment demonstrates the geom.Segment geometry for drawing line segments from (x, y) to (xend, yend).
Example segment demonstrates the geom.Segment geometry for drawing line segments from (x, y) to (xend, yend).
geometries/smooth command
Example smooth demonstrates the geom.smooth geometry.
Example smooth demonstrates the geom.smooth geometry.
geometries/step command
Example step demonstrates the geom.Step geometry.
Example step demonstrates the geom.Step geometry.
geometries/text command
Example text demonstrates the geom.Text geometry.
Example text demonstrates the geom.Text geometry.
geometries/tile command
Example tile demonstrates the geom.Tile heatmap geometry.
Example tile demonstrates the geom.Tile heatmap geometry.
geometries/violin command
Example violin demonstrates the geom.Violin geometry for showing mirrored kernel density estimates per group — like a boxplot but revealing the full distribution shape.
Example violin demonstrates the geom.Violin geometry for showing mirrored kernel density estimates per group — like a boxplot but revealing the full distribution shape.
multiline command
Example: Multi-Line Plot
Example: Multi-Line Plot
phase2_features command
Phase 2: Coordinates, Faceting, Themes, Guides, Aesthetics, LegendPosition
Phase 2: Coordinates, Faceting, Themes, Guides, Aesthetics, LegendPosition
phase2_geometries command
Phase 2: Geometries — Point, Line, Step, Bar, Histogram, Area, Density, Rug, HLine, VLine, Text, BoxPlot, Smooth
Phase 2: Geometries — Point, Line, Step, Bar, Histogram, Area, Density, Rug, HLine, VLine, Text, BoxPlot, Smooth
phase2_scales command
Phase 2: Scales — Linear, Log10, Sqrt, Reverse, Discrete
Phase 2: Scales — Linear, Log10, Sqrt, Reverse, Discrete
phase2_statistics command
Phase 2: Statistics — Identity, Bin/Count, Density (KDE), Smooth (LOESS), Summary, BoxPlot
Phase 2: Statistics — Identity, Bin/Count, Density (KDE), Smooth (LOESS), Summary, BoxPlot
phase4_pipeline command
Phase 4 Pipeline: System Columns (PANEL, group) & Position Adjustments
Phase 4 Pipeline: System Columns (PANEL, group) & Position Adjustments
phase5_transforms command
Phase 5: Composable Stat Transforms — Filter, Sort, Group, Normalize, Stack, TopN, Select, Ribbon, Difference
Phase 5: Composable Stat Transforms — Filter, Sort, Group, Normalize, Stack, TopN, Select, Ribbon, Difference
phase6_color_scales command
Example: Phase 6 — Colour Scales & Legends
Example: Phase 6 — Colour Scales & Legends
reference_lines command
Reference Lines — HLine, VLine, and ABLine examples.
Reference Lines — HLine, VLine, and ABLine examples.
scale_config command
Phase 5a: Scale Configuration — Breaks, Labels, Formatter, Expand, MinorBreaks, ClipBounds, and Binned.
Phase 5a: Scale Configuration — Breaks, Labels, Formatter, Expand, MinorBreaks, ClipBounds, and Binned.
secondary_axis command
Example: Secondary Y-Axis.
Example: Secondary Y-Axis.
showcase command
Example: Feature Showcase
Example: Feature Showcase
tabular_figures command
Tabular Figures Example
Tabular Figures Example
temporal/date command
Example date demonstrates the DTypeDate column using NewDateFromString and NewDateFromTime, plotting monthly metrics with calendar-aligned ticks.
Example date demonstrates the DTypeDate column using NewDateFromString and NewDateFromTime, plotting monthly metrics with calendar-aligned ticks.
temporal/nyt_deaths command
Example nyt_deaths demonstrates a journalism-style timeseries plot representing the 2020 excess deaths peak in New York City, styled after the New York Times visualizations with the "newsroom" theme.
Example nyt_deaths demonstrates a journalism-style timeseries plot representing the 2020 excess deaths peak in New York City, styled after the New York Times visualizations with the "newsroom" theme.
temporal/scale command
Example scale demonstrates explicit use of ScaleX(scale.DateTime, ...) with custom options, and the OOB policies (Censor, Squish, Keep).
Example scale demonstrates explicit use of ScaleX(scale.DateTime, ...) with custom options, and the OOB policies (Censor, Squish, Keep).
temporal/time command
Example time demonstrates DTypeTime (time-of-day) columns, plotting intraday patterns with nanoseconds-since-midnight values.
Example time demonstrates DTypeTime (time-of-day) columns, plotting intraday patterns with nanoseconds-since-midnight values.
temporal/timestamp command
Example timestamp demonstrates creating a time-series plot with timestamps parsed from strings.
Example timestamp demonstrates creating a time-series plot with timestamps parsed from strings.
themes command
Example: Theme Showcase
Example: Theme Showcase
Package facet splits a dataset into subsets for "small multiple" panel layouts.
Package facet splits a dataset into subsets for "small multiple" panel layouts.
Package fonts provides a cross-platform, pure-Go typography subsystem.
Package fonts provides a cross-platform, pure-Go typography subsystem.
Package geom provides geometry specifications for the Grammar of Graphics.
Package geom provides geometry specifications for the Grammar of Graphics.
Package output provides rendering output abstractions for exporting and displaying plots.
Package output provides rendering output abstractions for exporting and displaying plots.
Package scale provides scale transformations that map data values to visual aesthetic values.
Package scale provides scale transformations that map data values to visual aesthetic values.
Package stat provides composable statistical transforms for the Grammar of Graphics.
Package stat provides composable statistical transforms for the Grammar of Graphics.
Package theme provides visual styling configurations for plots.
Package theme provides visual styling configurations for plots.

Jump to

Keyboard shortcuts

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