geom

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package geom provides geometry specifications for the Grammar of Graphics. Geometries define how data is visually represented — as points, lines, bars, areas, etc. Each geom is a pure declarative specification; it holds no rendering logic. The rendering pipeline reads the spec and dispatches drawing operations to the [canvas.Canvas] backend.

Every geom constructor returns a Layer that can be added to a plot:

p := ggplot.New(ds, aes.X("x"), aes.Y("y")).
    Layer(geom.Point()).
    Layer(geom.Line())

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterGeomType

func RegisterGeomType(t Type, relevantOpts OptFlag)

RegisterGeomType registers a custom geometry type with its relevant option flags. This makes geom.Type open: third-party packages can define new geometry types that participate in option validation via Layer.Validate.

Combined with [ggplot.RegisterDrawer], this enables fully custom geoms:

// In your package init():
const TypeViolin geom.Type = "violin"
geom.RegisterGeomType(TypeViolin, geom.OptColor|geom.OptFill|geom.OptAlpha|geom.OptWidth)
ggplot.RegisterDrawer(TypeViolin, myViolinDrawer)

Types

type FillSetup added in v0.0.5

type FillSetup interface {
	Setup(allXs, allYs [][]float64)
}

FillSetup is optionally implemented by position adjustments that need a pre-pass over all groups before per-group Adjust calls.

type Layer

type Layer struct {
	Geom     Type              // geometry type (point, line, bar, etc.)
	Pipeline []stat.Transform  // ordered chain of transforms; nil = identity
	Position Pos               // position adjustment
	Params   Params            // visual parameters specific to this geometry
	Mapping  map[string]string // per-layer aesthetic overrides (channel → column)
	// contains filtered or unexported fields
}

Layer represents a declarative layer specification produced by a geom constructor. It carries the geometry type, an ordered transform pipeline, position adjustment, per-layer aesthetic mappings, and visual parameters.

func ABLine added in v0.0.2

func ABLine(opts ...Opt) Layer

ABLine creates a reference line defined by y = slope*x + intercept. Use WithIntercept for the y-intercept and WithSlope for the slope.

Example:

geom.ABLine(geom.WithIntercept(0), geom.WithSlope(1.5), geom.WithColor("#9B59B6"))

Relevant options: WithIntercept, WithSlope, WithColor, WithAlpha, WithLineWidth, WithLabel.

func Area

func Area(opts ...Opt) Layer

Area creates a filled area geometry layer.

Relevant options: WithColor, WithFill, WithAlpha, WithLineWidth.

func AreaX added in v0.0.5

func AreaX(pipeline []stat.Transform, opts ...Opt) Layer

AreaX creates a filled-area mark with horizontal orientation. This is the horizontal counterpart of AreaY.

geom.AreaX([]stat.Transform{stat.DensityY()})  // horizontal density fill

func AreaY added in v0.0.5

func AreaY(pipeline []stat.Transform, opts ...Opt) Layer

AreaY creates a filled-area mark with a transform pipeline. With DensityX, this becomes a filled KDE curve. With BinX, a filled histogram outline.

geom.AreaY(stat.DensityX())               // filled density
geom.AreaY(stat.BinX(stat.WithBins(40)))  // filled histogram

func Bar

func Bar(opts ...Opt) Layer

Bar creates a bar chart geometry layer. Default stat: count. Default position: stack.

Relevant options: WithColor, WithFill, WithAlpha, WithWidth, WithLineWidth.

func Boxplot

func Boxplot(opts ...Opt) Layer

Boxplot creates a box-and-whisker geometry layer. Default transform: BoxplotY with Tukey whiskers.

Relevant options: WithColor, WithFill, WithAlpha, WithWidth, WithLineWidth.

func Col

func Col(opts ...Opt) Layer

Col creates a column geometry layer that uses raw Y values (stat: identity). This is equivalent to ggplot2's geom_col(). Use Bar when you want automatic counting/aggregation, and Col when you have pre-computed values.

Default stat: identity. Default position: stack.

Relevant options: WithColor, WithFill, WithAlpha, WithWidth, WithLineWidth.

func Density

func Density(opts ...Opt) Layer

Density creates a kernel density estimation geometry layer.

Relevant options: WithColor, WithFill, WithAlpha, WithLineWidth.

func Difference added in v0.0.5

func Difference(pipeline []stat.Transform, opts ...Opt) Layer

Difference creates a layer that fills the area between two series, coloring positive and negative differences. Requires ymin and ymax columns in the pipeline output.

geom.Difference([]stat.Transform{stat.DeltaXY()}, geom.WithAlpha(0.5))

func ErrorBar added in v0.0.5

func ErrorBar(opts ...Opt) Layer

ErrorBar creates an error bar geometry layer. Each row draws a vertical or horizontal line from (x, ymin) to (x, ymax) with small caps.

Required aesthetics: x, ymin, ymax. Relevant options: WithColor, WithAlpha, WithLineWidth, WithWidth, WithOrientation.

func HLine

func HLine(opts ...Opt) Layer

HLine creates a horizontal reference line at the given Y intercept.

Example:

geom.HLine(geom.WithIntercept(0), geom.WithColor("#CC0000"))

Relevant options: WithIntercept, WithColor, WithAlpha, WithLineWidth, WithLabel.

func Histogram

func Histogram(opts ...Opt) Layer

Histogram creates a binned histogram geometry layer. Default transform: BinX(WithBins(30)). Default position: stack.

Relevant options: WithColor, WithFill, WithAlpha, WithWidth, WithLineWidth.

func Line

func Line(opts ...Opt) Layer

Line creates a connected line geometry layer.

Relevant options: WithColor, WithAlpha, WithLineWidth, WithSize.

func LineX added in v0.0.5

func LineX(pipeline []stat.Transform, opts ...Opt) Layer

LineX creates a connected-line mark with horizontal orientation. This is the horizontal counterpart of LineY.

geom.LineX([]stat.Transform{stat.GroupY("mean")})  // horizontal mean line

func LineY added in v0.0.5

func LineY(pipeline []stat.Transform, opts ...Opt) Layer

LineY creates a connected-line mark with a transform pipeline. With BinX, this becomes a frequency polygon. With SmoothXY, a regression line.

geom.LineY(stat.BinX(stat.WithBins(40)))  // frequency polygon
geom.LineY(stat.SmoothXY())               // regression line

func Point

func Point(opts ...Opt) Layer

Point creates a scatter point geometry layer. Default stat: identity. Default position: identity.

Relevant options: WithColor, WithFill, WithAlpha, WithSize, WithShape.

func PointY added in v0.0.5

func PointY(pipeline []stat.Transform, opts ...Opt) Layer

PointY creates a scatter point mark with a transform pipeline. With GroupX, this becomes a grouped aggregate scatter.

geom.PointY(stat.GroupX("mean"))           // mean per x
geom.PointY(stat.BinX(stat.WithBins(40))) // dot plot of bin centers

func Polygon

func Polygon(opts ...Opt) Layer

Polygon creates a closed polygon geometry layer.

Relevant options: WithColor, WithFill, WithAlpha, WithLineWidth.

func RectX added in v0.0.5

func RectX(pipeline []stat.Transform, opts ...Opt) Layer

RectX creates a rectangle mark anchored at x. This is the horizontal counterpart of RectY. With StackX, produces a horizontally stacked bar.

geom.RectX([]stat.Transform{stat.BinY(stat.WithBins(40))})  // horizontal histogram
geom.RectX([]stat.Transform{stat.Count()})                   // horizontal bar chart

func RectY added in v0.0.5

func RectY(pipeline []stat.Transform, opts ...Opt) Layer

RectY creates a rectangle mark anchored at y. The transform defines what data flows into the rectangles. With no transform, it renders pre-computed x/y values (equivalent to Col).

geom.RectY(stat.BinX(stat.WithBins(40)))   // histogram
geom.RectY(stat.Count())                    // bar chart
geom.RectY(stat.NormalizeY(), stat.BinX())  // proportions

func RibbonY added in v0.0.5

func RibbonY(pipeline []stat.Transform, opts ...Opt) Layer

RibbonY creates a filled band between ymin and ymax columns. Used for confidence intervals, prediction bands, error envelopes, etc.

geom.RibbonY([]stat.Transform{stat.SmoothXY()}, geom.WithAlpha(0.3))

func Rug

func Rug(opts ...Opt) Layer

Rug creates a rug (marginal tick) geometry layer.

Relevant options: WithColor, WithAlpha, WithLineWidth.

func Segment added in v0.0.5

func Segment(opts ...Opt) Layer

Segment creates a line-segment geometry layer. Each row draws a line from (x, y) to (xend, yend).

Required aesthetics: x, y, xend, yend. Relevant options: WithColor, WithAlpha, WithLineWidth.

func Smooth

func Smooth(opts ...Opt) Layer

Smooth creates a smoothed trendline geometry layer. Default transform: SmoothXY with method "lm".

Relevant options: WithColor, WithAlpha, WithLineWidth, WithSize.

func Step

func Step(opts ...Opt) Layer

Step creates a step-function line geometry layer.

Relevant options: WithColor, WithAlpha, WithLineWidth, WithSize.

func Text

func Text(opts ...Opt) Layer

Text creates a text label geometry layer.

Relevant options: WithColor, WithAlpha, WithFontSize, WithFontFamily, WithAngle.

func Tile added in v0.0.5

func Tile(opts ...Opt) Layer

Tile creates a heatmap-cell geometry layer. Each row maps to a filled rectangle at (x, y) whose color comes from a continuous color scale.

Required aesthetics: x, y, fill (or a continuous color column). Relevant options: WithColor, WithFill, WithAlpha.

func VLine

func VLine(opts ...Opt) Layer

VLine creates a vertical reference line at the given X intercept.

Example:

geom.VLine(geom.WithIntercept(5), geom.WithColor("#006600"))

Relevant options: WithIntercept, WithColor, WithAlpha, WithLineWidth, WithLabel.

func (*Layer) Validate

func (l *Layer) Validate() []string

Validate checks if the configured params are meaningful for this geometry type and returns a list of warning messages for irrelevant options.

Example:

layer := geom.Point(geom.WithWidth(0.5))  // width is for bars, not points
warnings := layer.Validate()
// warnings = ["geom_point: WithWidth has no effect (relevant for: bar, histogram)"]

func (*Layer) Warnings

func (l *Layer) Warnings() []string

Warnings returns any validation warnings generated during construction.

type Opt

type Opt func(*Layer)

Opt is a functional option for configuring geometry layers.

func Stat added in v0.0.5

func Stat(transforms ...stat.Transform) Opt

Stat sets an explicit transform pipeline for this layer, overriding any defaults from sugar options (WithBins, WithMethod, etc.). Use this for advanced composition when the sugar options are insufficient.

geom.Histogram(geom.Stat(stat.BinX(stat.WithBins(50)), stat.Normalize()))

func WithAlpha

func WithAlpha(a float64) Opt

WithAlpha sets the opacity.

func WithAngle

func WithAngle(deg float64) Opt

WithAngle sets the text rotation angle in degrees.

func WithBandwidth added in v0.0.5

func WithBandwidth(bw float64) Opt

WithBandwidth sets the KDE bandwidth. Relevant for Density.

func WithBins

func WithBins(n int) Opt

WithBins sets the number of histogram bins. Relevant for Histogram.

func WithColor

func WithColor(hex string) Opt

WithColor sets a fixed color override.

func WithDensityPoints added in v0.0.5

func WithDensityPoints(n int) Opt

WithDensityPoints sets the output point count for KDE. Relevant for Density.

func WithFill

func WithFill(hex string) Opt

WithFill sets a fixed fill color override.

func WithFontFamily

func WithFontFamily(family string) Opt

WithFontFamily sets the text font family.

func WithFontSize

func WithFontSize(size float64) Opt

WithFontSize sets the text font size.

func WithGap

func WithGap(g float64) Opt

WithGap sets the gap between bars as a fraction [0, 1]. 0 means bars touch (no gap), 1 means 100% gap (bars invisible). The bar width is derived as 1 - gap. Default gap is 0.2.

func WithIntercept

func WithIntercept(v float64) Opt

WithIntercept sets the intercept value for reference lines. For HLine, this is the Y value. For VLine, this is the X value.

func WithLabel

func WithLabel(name string) Opt

WithLabel sets a legend label for this layer. When used together with WithColor, a legend entry is generated even without aes.Color grouping. This is the idiomatic way to add legends in wide-format multi-layer plots.

func WithLineWidth

func WithLineWidth(w float64) Opt

WithLineWidth sets the stroke width.

func WithMethod

func WithMethod(m string) Opt

WithMethod sets the smoothing method ("lm" or "loess"). Relevant for Smooth.

func WithNotch

func WithNotch(b bool) Opt

WithNotch enables notched boxplot display. Relevant for Boxplot.

func WithOrientation

func WithOrientation(o Orientation) Opt

WithOrientation sets the axis extension direction for directional geoms. Horizontal makes bars grow rightward, boxplots lay sideways, etc.

func WithPosition

func WithPosition(p Pos) Opt

WithPosition sets the position adjustment for this layer.

func WithShape

func WithShape(shape string) Opt

WithShape sets the point shape.

func WithSize

func WithSize(s float64) Opt

WithSize sets the point radius. Use WithLineWidth for stroke width.

func WithSlope added in v0.0.2

func WithSlope(s float64) Opt

WithSlope sets the slope for ABLine. The line equation is y = slope*x + intercept.

func WithSmoothPoints added in v0.0.5

func WithSmoothPoints(n int) Opt

WithSmoothPoints sets the output point count for smoothing. Relevant for Smooth.

func WithWhisker

func WithWhisker(w string) Opt

WithWhisker sets the whisker extent type (e.g. "tukey"). Relevant for Boxplot.

func WithWidth

func WithWidth(w float64) Opt

WithWidth sets the relative bar width [0, 1].

type OptFlag

type OptFlag uint32

OptFlag tracks which parameters were explicitly set by the user. Exported so third-party packages can compose relevance masks for RegisterGeomType.

const (
	OptColor         OptFlag = 1 << iota // common
	OptFill                              // common
	OptAlpha                             // common
	OptLineWidth                         // common
	OptSize                              // point, (also sets LineWidth)
	OptShape                             // point
	OptWidth                             // bar, histogram
	OptFontSize                          // text
	OptFontFamily                        // text
	OptAngle                             // text
	OptOrientation                       // bar, histogram, boxplot, area, density, rug
	OptBins                              // histogram
	OptMethod                            // smooth
	OptSmoothPoints                      // smooth
	OptBandwidth                         // density
	OptDensityPoints                     // density
	OptWhisker                           // boxplot
	OptNotch                             // boxplot
)

OptColor tracks whether WithColor was set.

type Orientation

type Orientation string

Orientation controls which axis a directional geom extends along.

const (
	Vertical   Orientation = "v" // default: bars grow upward, boxplots are vertical
	Horizontal Orientation = "h" // bars grow rightward, boxplots are horizontal
)

Vertical is the default orientation: bars grow upward.

type Params

type Params struct {
	// Common
	Color     string  // hex color override (e.g., "#4C72B0")
	Fill      string  // hex fill color override
	Alpha     float64 // opacity [0, 1]
	LineWidth float64 // stroke width in pixels

	// Point-specific
	Size  float64 // point radius in pixels (default = 3)
	Shape string  // "circle", "square", "triangle", "diamond" (default = "circle")

	// Bar/Histogram/Rect-specific
	Width float64 // relative bar width [0, 1] (default = 0.8)
	Gap   float64 // gap between bars [0, 1] (0 = touching, 1 = invisible; default = 0.2)
	Inset float64 // pixel inset per side between adjacent rects (default = 0; 0.5 for continuous bins)

	// Text-specific
	FontSize   float64 // text font size in points
	FontFamily string  // font family name
	Angle      float64 // rotation angle in degrees

	// Orientation
	Orientation Orientation // "v" (default) or "h" — controls axis extension direction

	// Legend
	Label string // legend label for this layer (used with manual colors)

	// Reference lines
	Intercept float64 // y-intercept (hline) or x-intercept (vline)
	Slope     float64 // slope for abline (y = slope*x + intercept)
}

Params holds visual parameters for geometries. Not all fields apply to every geometry type; unused fields are ignored during rendering but Layer.Validate will emit warnings for irrelevant options.

Note: stat-specific parameters (bins, method, bandwidth, whisker, notch) are owned by their respective stat.Transform options, not by Params.

type Pos added in v0.0.5

type Pos interface {
	// Adjust modifies (x, y) positions for a single group within a layer.
	// groupIdx is the 0-based index of this group, nGroups is the total count.
	// width is the available bin width for dodging/stacking calculations.
	Adjust(xs, ys []float64, width float64, groupIdx, nGroups int) ([]float64, []float64)

	// String returns a human-readable label.
	String() string
}

Pos adjusts the positions of geometric elements to handle overlap. Each adjustment receives the raw data coordinates and group metadata, and returns adjusted coordinates.

func Dodge added in v0.0.5

func Dodge() Pos

Dodge returns a position that shifts groups side by side within each bin. This is the standard adjustment for grouped bar charts.

func Fill added in v0.0.5

func Fill() Pos

Fill returns a position that stacks groups and normalizes each x-bin to a total of 1.0 (100% stacked bar chart).

Fill is a two-phase adjustment:

  1. Setup phase: call [FillSetup.Setup] with all groups' (xs, ys) to compute totals.
  2. Adjust phase: call Adjust for each group in order.

If Setup is not called, Fill behaves like Stack (no normalization).

func IdentityPos added in v0.0.5

func IdentityPos() Pos

IdentityPos returns the identity position (no adjustment).

func Jitter added in v0.0.5

func Jitter(xAmount, yAmount float64) Pos

Jitter returns a position that adds random noise to (x, y) to reduce overplotting. The jitter is reproducible: same data length produces same offsets.

func NewPos added in v0.0.5

func NewPos(name PosName) Pos

NewPos creates a fresh Pos instance by name. This is used by the build pipeline to create per-panel-layer position instances (avoiding shared state across panels). Returns IdentityPos for unknown names.

func Nudge added in v0.0.5

func Nudge(dx, dy float64) Pos

Nudge returns a position that shifts all points by a fixed offset.

func Stack added in v0.0.5

func Stack() Pos

Stack returns a position that stacks groups vertically. Each group's y-values are offset by the cumulative sum of prior groups at the same x-value.

Stack is stateful: it accumulates offsets across successive Adjust calls. The build pipeline must create a fresh Stack() instance per panel-layer to avoid cross-panel contamination.

type PosName added in v0.0.5

type PosName string

PosName identifies a position adjustment type for factory lookup.

const (
	PosIdentity PosName = "identity"
	PosDodge    PosName = "dodge"
	PosStack    PosName = "stack"
	PosFill     PosName = "fill"
	PosJitter   PosName = "jitter"
	PosNudge    PosName = "nudge"
)

Position adjustment names.

type Stacker added in v0.0.5

type Stacker interface {
	AdjustStack(xs, ys []float64, width float64, groupIdx, nGroups int) (adjXs, yMin, yMax []float64)
}

Stacker is optionally implemented by positions that produce stacked output. When implemented, AdjustStack returns (adjustedXs, yMin, yMax) where yMin is the bottom of each bar and yMax is the top. The pipeline uses yMin to set the bar's base coordinate.

type Type

type Type string

Type identifies the kind of geometry.

const (
	TypePoint      Type = "point"
	TypeLine       Type = "line"
	TypeBar        Type = "bar"
	TypeHistogram  Type = "histogram"
	TypeArea       Type = "area"
	TypePolygon    Type = "polygon"
	TypeSmooth     Type = "smooth"
	TypeText       Type = "text"
	TypeBoxPlot    Type = "boxplot"
	TypeErrorBar   Type = "errorbar"
	TypeDensity    Type = "density"
	TypeTile       Type = "tile"
	TypeRug        Type = "rug"
	TypeSegment    Type = "segment"
	TypeStep       Type = "step"
	TypeHLine      Type = "hline"
	TypeVLine      Type = "vline"
	TypeABLine     Type = "abline"
	TypeRibbon     Type = "ribbon"     // filled band between ymin/ymax
	TypeDifference Type = "difference" // difference between two series
	TypeRect       Type = "rect"       // unified rectangle mark (replaces TypeBar/TypeHistogram for pipeline constructors)
)

TypePoint identifies a scatter point geometry.

Jump to

Keyboard shortcuts

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