zuzu

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 48 Imported by: 0 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README


Unit Tests Go Reference Releases Discord Discussion

About

zuzu draws charts and diagrams in pure Go, with no cgo. You give it a declarative spec, which says what to draw from which data. zuzu writes the chart as SVG or draws it as an image.

The spec follows Vega and Vega-Lite. A spec written for the Vega tools works with zuzu, as far as zuzu supports it. zuzu also reads the DOT language of Graphviz and every kind of diagram of Mermaid 12.3. docs/DIAGRAMS.md lists what it reads.

zuzu draws its own look, with a light and a dark mode and color schemes that you swap apart from the mode. It can also draw any chart or diagram as if by hand. It draws an image with okage, a pure Go port of resvg, and it measures and draws text in the fonts that it bundles. The same spec gives the same image on every machine of one architecture.

Add zuzu to a module:

go get github.com/xo/zuzu

Examples

The code below comes from the examples of the package, which go test runs. Each image is a PNG that Chart.Image drew from that code. The test TestTheReadmeImagesAreDrawn draws the images again with -update.

A chart from Vega-Lite

zuzu.Parse reads a Vega-Lite or a Vega spec, and Chart.Image draws it. The report lists each feature of the spec that zuzu did not draw.

ctx := context.Background()
src := []byte(`{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "width": 320,
  "height": 180,
  "data": {"values": [
    {"fruit": "Apples", "sold": 28},
    {"fruit": "Bananas", "sold": 55},
    {"fruit": "Cherries", "sold": 43},
    {"fruit": "Dates", "sold": 91},
    {"fruit": "Figs", "sold": 81}
  ]},
  "mark": "bar",
  "encoding": {
    "x": {"field": "fruit", "type": "nominal", "title": null, "axis": {"labelAngle": 0}},
    "y": {"field": "sold", "type": "quantitative"},
    "color": {"field": "fruit", "legend": null}
  }
}`)
chart, _, err := zuzu.Parse(src)
if err != nil {
	log.Fatal(err)
}
img, report, err := chart.Image(ctx)
if err != nil {
	log.Fatal(err)
}
for _, issue := range report {
	log.Println(issue)
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
	log.Fatal(err)
}
A bar chart of five fruits, each bar in its own color

png.Encode writes the image to any io.Writer, such as a file. A Chart does not change after Parse, so many goroutines can draw one Chart at the same time.

SVG

Chart.SVG writes the same chart as SVG:

var buf bytes.Buffer
report, err := chart.SVG(ctx, &buf)

The SVG names the font IBM Plex Sans, and a viewer that does not have the font draws the text in another one. Chart.Image draws the text in the bundled font, so the image looks the same everywhere.

A Mermaid diagram

zuzu.Parse finds a diagram of Mermaid or of DOT by its first word. Draw it as you draw a chart:

src := []byte(`flowchart TD
  A[Spec] --> B{Vega-Lite?}
  B -- yes --> C[Compile]
  B -- no --> D[Run]
  C --> D
  D --> E[(Scene)]`)
chart, _, err := zuzu.Parse(src)
A flowchart from a spec to a scene, through a choice between compile and run

A DOT graph

src := []byte(`digraph {
  rankdir=LR
  parse -> compile -> run -> scene
  scene -> svg
  scene -> image
}`)
chart, _, err := zuzu.Parse(src)
A graph from parse to scene, which leads to svg and to image

Dark mode and color schemes

A theme is a mode, light or dark, and a color scheme. The mode sets the background, the text and the axes. The scheme sets the colors of the data. Give either one to a render:

img, report, err := chart.Image(ctx,
	zuzu.WithMode(theme.Dark),
	zuzu.WithScheme(theme.Ember),
)
The light mode and the scheme zuzu The dark mode and the scheme ember
The bar chart in the light mode The bar chart in the dark mode with warm colors

theme.Schemes returns the names of the schemes, and theme.Lookup finds one by its name. docs/STYLE.md describes each one. Most schemes come from the styles of editor themes, such as catppuccin, solarized, gruvbox and tokyonight, and docs/SCHEMES.md lists them.

The hand-drawn look

zuzu.WithLook(theme.LookExcalidraw) draws each mark as if by hand, as Excalidraw does. The package text/excalifont holds the font of the look, Excalifont. Give it with zuzu.WithLookFont, so that zuzu measures and draws the text in it:

look := zuzu.WithLook(theme.LookExcalidraw)
font := zuzu.WithLookFont(theme.LookExcalidraw, excalifont.Font())
chart, _, err := zuzu.Parse(src, look, font)
The flowchart drawn as if by hand

The look works for a chart too. The SVG embeds the font, so a viewer draws the text in Excalifont.

Other fonts

zuzu draws its text in IBM Plex Sans. Four optional packages hold four other fonts, each with six faces: text/mono holds IBM Plex Mono, text/humanist holds Inter, text/serif holds IBM Plex Serif and text/rounded holds Nunito. Give one with zuzu.WithFont, so that zuzu measures and draws the text in it:

font := zuzu.WithFont(mono.Font())
chart, _, err := zuzu.Parse(src, font)

The SVG embeds the font. A program that does not import a package of a font does not hold the font.

To draw in a font that zuzu does not bundle, give zuzu.WithFonts a file system of font files. A text whose font names a family of the files draws in it, and the files also draw each character that the other fonts do not have. The package text/system returns the font folders of the platform, as in zuzu.WithFonts(system.Fonts()). The output then depends on the fonts of the machine.

Data from a loader

zuzu reads no file and makes no request of its own. A spec that names its data by url reads it through the loader that you give with zuzu.WithLoader. zuzu.FSLoader reads each url as a path in a file system that you choose:

src := []byte(`{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "width": 320,
  "height": 180,
  "data": {"url": "temps.csv"},
  "mark": {"type": "line", "point": true},
  "encoding": {
    "x": {"field": "month", "type": "ordinal", "sort": null, "title": null},
    "y": {"field": "temp", "type": "quantitative", "title": "°C"},
    "color": {"field": "city", "title": null}
  }
}`)
// Any fs.FS works, such as os.DirFS("data").
fsys := fstest.MapFS{"temps.csv": {Data: []byte(`month,city,temp
Jan,Oslo,-4
Feb,Oslo,-4
Mar,Oslo,0
Apr,Oslo,5
May,Oslo,11
Jun,Oslo,15
Jan,Rome,8
Feb,Rome,9
Mar,Rome,11
Apr,Rome,14
May,Rome,18
Jun,Rome,22
`)}}
chart, _, err := zuzu.Parse(src)
if err != nil {
	log.Fatal(err)
}
img, report, err := chart.Image(ctx, zuzu.WithLoader(zuzu.FSLoader(fsys)))
A line chart of the temperature of Oslo and Rome from January to June

zuzu.WithValues gives the rows of a dataset directly, without a loader. docs/API.md lists every option.

Design

zuzu has four stages. Each stage hands the next one a value that can be written as JSON:

  1. A front end reads Vega, Vega-Lite, DOT or Mermaid, and produces a spec in the shape of a Vega spec.
  2. The runtime loads the data, runs the transforms and the expressions, builds the scales and lays out the axes and the legends.
  3. The result is a scene graph: a tree of shapes with their final positions, sizes and colors.
  4. A renderer writes the scene graph as SVG, or draws it with okage.

zuzu runs static Vega, which is Vega without the events of a mouse or a keyboard, and the Vega-Lite that compiles to it. A corpus of 579 Vega-Lite specs and 87 Vega specs from vegagoja, with the output of vega.js for each, measures how far zuzu agrees with Vega. Later, zuzu will send live charts to a web browser and draw the results of a query for usql.

Documents

Document What it holds
docs/PLAN.md the plan, the architecture, the phases and the open questions
docs/API.md the public API
docs/EXPRESSIONS.md the expression language, and the choices for scripting beyond it
docs/decisions/ every decision, one file each, with an index
docs/BACKLOG.md the work that is known and not done
docs/STYLE.md the rules and the tokens of the look, the modes and the color schemes
docs/SCHEMES.md the color schemes from the styles of editor themes, with their colors and their sources
docs/DIAGRAMS.md the parts of DOT and of Mermaid that zuzu reads
docs/targets/ the target SVGs that show the look zuzu aims for
docs/survey/ the survey of other libraries, and the page that compares them
docs/UPSTREAM.md the rules for the Go code that zuzu copies from other projects, and the list of those projects
AGENTS.md the rules for a coding agent, which apply to a person too
CONTRIBUTING.md how to change zuzu

Contributing

Read CONTRIBUTING.md first. A change to the design is a decision first, and an open question goes to the maintainers.


Documentation

Overview

Package zuzu draws charts and diagrams from a declarative spec that follows Vega and Vega-Lite. It writes its own SVG (D10), and it draws an image with the drawing of okage directly, without the SVG (D11).

The plan is in docs/PLAN.md and the public API in docs/API.md.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromVega

func FromVega(spec *vega.Spec, opts ...Option) (*Chart, Report, error)

FromVega takes a Vega spec that a program built as Go values. It copies the spec, so a later change by the caller does not reach the Chart.

func FromVegaLite

func FromVegaLite(spec *vegalite.Spec, opts ...Option) (*Chart, Report, error)

FromVegaLite takes a Vega-Lite spec that a program built as Go values, and compiles it to Vega. The report names each part that zuzu did not compile, in the loose mode.

func Parse

func Parse(src []byte, opts ...Option) (*Chart, Report, error)

Parse reads a Vega or a Vega-Lite spec, or a diagram of DOT or Mermaid (D31). The $schema field decides between Vega and Vega-Lite, and the first word of a source finds a diagram. Another source needs WithDialect.

Example
package main

import (
	"fmt"
	"log"

	"github.com/xo/zuzu"
)

func main() {
	src := []byte(`{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "data": {"values": [{"a": "x", "b": 1}, {"a": "y", "b": 2}]},
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal"},
    "y": {"field": "b", "type": "quantitative"}
  }
}`)
	chart, report, err := zuzu.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(chart.Spec().Marks) > 0, len(report))
}
Output:
true 0
Example (Dot)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/xo/zuzu"
)

func main() {
	ctx := context.Background()
	src := []byte(`digraph {
  rankdir=LR
  parse -> compile -> run -> scene
  scene -> svg
  scene -> image
}`)
	chart, _, err := zuzu.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), len(report))
}
Output:
465 119 0
Example (Mermaid)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/xo/zuzu"
)

func main() {
	ctx := context.Background()
	src := []byte(`flowchart TD
  A[Spec] --> B{Vega-Lite?}
  B -- yes --> C[Compile]
  B -- no --> D[Run]
  C --> D
  D --> E[(Scene)]`)
	chart, _, err := zuzu.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), len(report))
}
Output:
174 446 0

Types

type Chart

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

Chart is a parsed spec. It does not change after Parse, so it is safe for concurrent use.

func (*Chart) Image

func (c *Chart) Image(ctx context.Context, opts ...RenderOption) (*image.RGBA, Report, error)

Image renders the chart and draws it with the direct renderer of okage (D11). The text draws in the bundled IBM Plex Sans (D16), the fonts of WithEmoji, the font of a look drawn by hand of WithLookFont, the font of WithFont and the fonts of WithFonts that a text draws in (D62). It draws in no other font of the system, so that a chart gives the same pixels on every machine with the same fonts. A character that no font has draws nothing (D32). The pixels are premultiplied, as image.RGBA expects.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"image/png"
	"log"

	"github.com/xo/zuzu"
)

func main() {
	ctx := context.Background()
	src := []byte(`{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "width": 320,
  "height": 180,
  "data": {"values": [
    {"fruit": "Apples", "sold": 28},
    {"fruit": "Bananas", "sold": 55},
    {"fruit": "Cherries", "sold": 43},
    {"fruit": "Dates", "sold": 91},
    {"fruit": "Figs", "sold": 81}
  ]},
  "mark": "bar",
  "encoding": {
    "x": {"field": "fruit", "type": "nominal", "title": null, "axis": {"labelAngle": 0}},
    "y": {"field": "sold", "type": "quantitative"},
    "color": {"field": "fruit", "legend": null}
  }
}`)
	chart, _, err := zuzu.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, issue := range report {
		log.Println(issue)
	}
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		log.Fatal(err)
	}
	fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), len(report))
}
Output:
358 231 0

func (*Chart) NewView

func (c *Chart) NewView(ctx context.Context, opts ...RenderOption) (*View, Report, error)

NewView runs the spec and keeps its state.

func (*Chart) Render

func (c *Chart) Render(ctx context.Context, opts ...RenderOption) (*scene.Scene, Report, error)

Render runs the spec and returns the scene graph.

func (*Chart) SVG

func (c *Chart) SVG(ctx context.Context, w io.Writer, opts ...RenderOption) (Report, error)

SVG renders the chart and writes it as SVG. In a look drawn by hand, the SVG embeds the font of the look, such as Excalifont, and else the font of WithFont, so that a viewer that lacks the font draws the text in it (D43, D58). It embeds each font of WithFonts that a text draws in as its family too, and a font of WithFonts that draws only a character that the other fonts do not have when WithEmbedCoverFonts asks for it (D62). A text with a limit measures with the fonts of WithEmoji, as the layout measured it, so that it is cut at the same place (D32).

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/xo/zuzu"
)

func main() {
	ctx := context.Background()
	chart, _, err := zuzu.Parse([]byte("flowchart LR\n  A --> B"))
	if err != nil {
		log.Fatal(err)
	}
	var buf bytes.Buffer
	report, err := chart.SVG(ctx, &buf)
	if err != nil {
		log.Fatal(err)
	}
	head, _, _ := strings.Cut(buf.String(), " font-family")
	fmt.Println(head)
	fmt.Println(len(report))
}
Output:
<svg xmlns="http://www.w3.org/2000/svg" width="277" height="47" viewBox="0 0 277 47"
0

func (*Chart) Spec

func (c *Chart) Spec() *vega.Spec

Spec returns a copy of the Vega spec, to read or to debug.

type Dialect

type Dialect int

Dialect is the language of a spec.

const (
	// Vega is a Vega spec.
	Vega Dialect = iota + 1
	// VegaLite is a Vega-Lite spec.
	VegaLite
	// DOT is a graph in the DOT language of Graphviz (D31).
	DOT
	// Mermaid is a diagram of Mermaid (D31).
	Mermaid
)

The dialects.

func Sniff added in v0.2.0

func Sniff(prefix []byte) (Dialect, bool)

Sniff returns the dialect of a source from its first bytes, as a detector of a type of file does: DOT or Mermaid from the first word, and Vega or Vega-Lite from a $schema in the first bytes. It needs no more than the first 512 bytes, and returns false when they do not decide.

type Error

type Error string

Error is an error of the package zuzu.

const (
	// ErrUnknownDialect is the error of a spec whose $schema names neither
	// Vega nor Vega-Lite, and of a spec with no $schema and no WithDialect.
	ErrUnknownDialect Error = "unknown spec dialect"
	// ErrNoLoader is the error of a spec that names data by url, when the
	// render has no loader (D25).
	ErrNoLoader Error = "no loader for url data"
	// ErrCycle is the error of a signal, a dataset or a scale that depends
	// on itself.
	ErrCycle Error = "cycle in the spec"
	// ErrUnknownName is the error of a reference to a signal, a dataset or a
	// scale that the spec does not have.
	ErrUnknownName Error = "unknown name"
	// ErrNoGlyph is the error of a character of a text that no font of the
	// render has, in the strict mode. In the loose mode, the character
	// draws nothing and the report names it once (D32).
	ErrNoGlyph Error = "no font has the character"
	// ErrNoNow is the error of an expression that calls now() when the
	// parse has no WithNow, in the strict mode. In the loose mode, now()
	// gives 0 and the report names the expression once (D38).
	ErrNoNow Error = "no time of the render"
	// ErrNoLookFont is the warning of a look drawn by hand when the render
	// has no font of the look, which WithLookFont gives. The look draws its
	// text in the font that the scheme names and WithFonts gives, or else
	// in IBM Plex Sans, and the warning names that font. Nothing is
	// dropped, and the report holds the warning in either mode, never an
	// error (D40, D62).
	ErrNoLookFont Error = "no font of the look"
)

The errors of the package. The errors of a spec are in the package vega.

func (Error) Error

func (err Error) Error() string

Error satisfies the error interface.

type IconLoader

type IconLoader interface {
	LoadIcon(ctx context.Context, req IconRequest) (io.ReadCloser, error)
}

IconLoader gives the icons that no pack of WithIcons holds (D31). zuzu asks it once for each icon of a render, by its prefix and its name, and it gives the bytes from wherever it chooses. zuzu itself reads no file and makes no request.

func FSIconLoader

func FSIconLoader(fsys fs.FS) IconLoader

FSIconLoader reads an icon from fsys: the SVG <prefix>/<name>.svg, or else the pack of Iconify <prefix>.json. The caller chooses fsys, so zuzu still reads only what the caller allows.

type IconLoaderFunc

type IconLoaderFunc func(context.Context, IconRequest) (io.ReadCloser, error)

IconLoaderFunc makes an IconLoader of a function.

func (IconLoaderFunc) LoadIcon

func (f IconLoaderFunc) LoadIcon(ctx context.Context, req IconRequest) (io.ReadCloser, error)

LoadIcon calls the function.

type IconRequest

type IconRequest struct {
	Prefix, Name string
}

IconRequest names an icon: aws and lambda, for aws:lambda.

type LoadRequest

type LoadRequest struct {
	// URL is the url of the spec, as written.
	URL string
	// Format is csv, tsv, json or topojson, from the spec, or image for the
	// image of a node.
	Format string
	// Name is the name of the dataset.
	Name string
}

LoadRequest says what a spec asks for.

type Loader

type Loader interface {
	Load(ctx context.Context, req LoadRequest) (io.ReadCloser, error)
}

Loader reads the data that a spec names by url (D25). zuzu reads no file and makes no request of its own.

func FSLoader

func FSLoader(fsys fs.FS) Loader

FSLoader reads each url as a path in fsys. The caller chooses fsys, so zuzu still reads only what the caller allows. A url with a scheme, such as https:, is an error.

type LoaderFunc

type LoaderFunc func(context.Context, LoadRequest) (io.ReadCloser, error)

LoaderFunc makes a Loader of a function.

func (LoaderFunc) Load

func (f LoaderFunc) Load(ctx context.Context, req LoadRequest) (io.ReadCloser, error)

Load calls the function.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a setting of Parse.

func WithDialect

func WithDialect(d Dialect) Option

WithDialect sets the dialect of a spec that has no $schema.

func WithFunction

func WithFunction(name string, fn expr.Func) Option

WithFunction adds a Go function that an expression can call by name. It takes the place of a built in function of the same name.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets where zuzu logs.

func WithMath added in v0.7.5

func WithMath(f *text.MathFont) Option

WithMath gives a parse a font of math, so that the math of KaTeX in a label of Mermaid, written as $$...$$, draws as math (D36). The package text/math gives the font, STIX Two Math:

c, report, err := zuzu.Parse(src, zuzu.WithMath(math.Font()))

It is an option of Parse, because some kinds of Mermaid lay out their labels when they compile. The chart keeps the font, and each render of it uses the font. Without the font, a label with math draws its source, and the report names it. A program that does not import text/math does not hold the font.

func WithNow added in v0.8.0

func WithNow(t time.Time) Option

WithNow gives a parse the time of the render (D38). A gantt of Mermaid with the time draws the marker of today, and a date of its dateFormat that has no day, such as HH:mm, takes the day of the time, as in Mermaid. The gantt takes the day and the hour that the time has in its own time zone. The function now() of an expression gives the time, in milliseconds since 1970.

It is an option of Parse, because a gantt lays out when it compiles. The chart keeps the time, and each render of it uses the time. Without the time, a gantt draws no marker and puts a date with no day on 1970-01-01, and now() gives 0, so that the same spec gives the same bytes. The report names each expression that calls now() with no time, and in the strict mode such a call is an error that wraps ErrNoNow. The zero time is no time.

func WithStrict

func WithStrict(strict bool) Option

WithStrict sets the feature mode (D26). In the strict mode, a feature that zuzu does not support is an error. In the loose mode, the default, zuzu skips it and names it in the report.

type RenderOption

type RenderOption interface {
	// contains filtered or unexported methods
}

RenderOption is a setting of a render.

func WithBackground added in v0.2.0

func WithBackground(c color.Color) RenderOption

WithBackground sets the background of the chart, over the background of the theme and of the spec, and over zuzu.background in the config of the spec. A color with an alpha of 0 draws no background, and nil keeps the background of the theme and of the spec. The boxes under the labels of a diagram and the open arrowheads take an opaque color too, so that they match the background.

func WithEmbedCoverFonts added in v0.12.0

func WithEmbedCoverFonts(embed bool) RenderOption

WithEmbedCoverFonts says whether the SVG of SVG embeds each font of WithFonts that draws only characters that the other fonts of the render do not have (D62). By default it does not embed such a font, which can be large, such as a font of CJK of 15 MB. Each text still names its family, so a viewer that has the font draws the character. With true, the SVG embeds the font in a rule @font-face, as it embeds the font of WithFont (D43). The PNG of Image draws the character in both cases. A family that the font of a text names, and that the set gives, is always embedded, as WithFonts says.

func WithIconLoader

func WithIconLoader(l IconLoader) RenderOption

WithIconLoader sets how a render loads the icons that no pack holds.

func WithIcons

func WithIcons(name string, p *icon.Pack) RenderOption

WithIcons gives a pack of icons to a render, under a name that replaces the prefix of the pack, as Mermaid does (D31). A diagram names an icon of the pack as name:icon.

func WithLoader

func WithLoader(l Loader) RenderOption

WithLoader sets how the data of a url is read (D25).

Example
package main

import (
	"context"
	"fmt"
	"log"
	"testing/fstest"

	"github.com/xo/zuzu"
)

func main() {
	ctx := context.Background()
	src := []byte(`{
  "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
  "width": 320,
  "height": 180,
  "data": {"url": "temps.csv"},
  "mark": {"type": "line", "point": true},
  "encoding": {
    "x": {"field": "month", "type": "ordinal", "sort": null, "title": null},
    "y": {"field": "temp", "type": "quantitative", "title": "°C"},
    "color": {"field": "city", "title": null}
  }
}`)
	// Any fs.FS works, such as os.DirFS("data").
	fsys := fstest.MapFS{"temps.csv": {Data: []byte(`month,city,temp
Jan,Oslo,-4
Feb,Oslo,-4
Mar,Oslo,0
Apr,Oslo,5
May,Oslo,11
Jun,Oslo,15
Jan,Rome,8
Feb,Rome,9
Mar,Rome,11
Apr,Rome,14
May,Rome,18
Jun,Rome,22
`)}}
	chart, _, err := zuzu.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx, zuzu.WithLoader(zuzu.FSLoader(fsys)))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), len(report))
}
Output:
361 231 0

func WithLocale

func WithLocale(l format.Locale) RenderOption

WithLocale sets the locale of numbers and dates (D27).

func WithLocation

func WithLocation(loc *time.Location) RenderOption

WithLocation sets the time zone of local time (D27). The default is the zone of the system.

func WithMode

func WithMode(m theme.Mode) RenderOption

WithMode sets the light or the dark mode (D14). It wins over the mode that the spec asks for with zuzu.mode in its config, such as the dark theme of a Mermaid diagram (D32).

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/xo/zuzu"
	"github.com/xo/zuzu/theme"
)

func main() {
	ctx := context.Background()
	chart, _, err := zuzu.Parse([]byte("flowchart LR\n  A --> B"))
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx, zuzu.WithMode(theme.Dark))
	if err != nil {
		log.Fatal(err)
	}
	bg := img.RGBAAt(0, 0)
	fmt.Printf("#%02x%02x%02x %d\n", bg.R, bg.G, bg.B, len(report))
}
Output:
#10141b 0

func WithRandom

func WithRandom(fn func() rand.Source) RenderOption

WithRandom sets the function that makes the source of random numbers of a render (D28). Each render calls it once.

func WithRenderLogger

func WithRenderLogger(l *slog.Logger) RenderOption

WithRenderLogger sets where a render logs.

func WithResultSet

func WithResultSet(name string, rs ResultSet) RenderOption

WithResultSet gives the rows of a named dataset, read from the result of a query. zuzu reads it once, and the caller closes it.

func WithScale added in v0.3.0

func WithScale(scale float64) RenderOption

WithScale draws the image of Image at a scale, as a ratio of device pixels to the pixels of the chart, such as 2 for a screen of high density. The layout, the fonts and the size of the scene do not change, and the image has the size of the scene times the scale. The SVG of SVG has a viewBox, so a viewer scales it, and the scale does not change it. A scale that is not more than zero, or not finite, is an error of Image.

func WithScheme

func WithScheme(s theme.Scheme) RenderOption

WithScheme sets the color scheme (D14). It wins over the scheme that the spec asks for with zuzu.scheme in its config, such as the forest theme of a Mermaid diagram (D32).

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/xo/zuzu"
	"github.com/xo/zuzu/theme"
)

func main() {
	ctx := context.Background()
	chart, _, err := zuzu.Parse([]byte("flowchart LR\n  A --> B"))
	if err != nil {
		log.Fatal(err)
	}
	img, report, err := chart.Image(ctx,
		zuzu.WithMode(theme.Dark),
		zuzu.WithScheme(theme.Ember),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), len(report))
}
Output:
277 47 0

func WithSize

func WithSize(width, height float64) RenderOption

WithSize sets the size of the chart, in place of its width and height.

func WithValues

func WithValues(name string, rows []map[string]any) RenderOption

WithValues gives the rows of a named dataset. They take the place of the values or the url of the dataset in the spec, and its transforms still run.

type Report

type Report = vega.Report

Report lists what zuzu did not draw in the loose mode, and what it warns of in either mode (D26). A warning, such as an issue that wraps ErrNoLookFont, draws in full in another way, so the strict mode reports it and does not turn it into an error.

type ResultSet

type ResultSet interface {
	Columns() ([]string, error)
	Next() bool
	Scan(dest ...any) error
	Err() error
}

ResultSet is the result of a query. *sql.Rows satisfies it.

type SharedOption added in v0.8.0

type SharedOption interface {
	Option
	RenderOption
}

SharedOption is a setting of both Parse and a render, such as WithEmoji.

func WithEmoji added in v0.6.0

func WithEmoji(f *text.Fallback) SharedOption

WithEmoji gives a parse or a render a font for the emoji, so that an emoji draws in color (D32). The package text/emoji gives the font, Noto Color Emoji:

c, report, err := zuzu.Parse(src, zuzu.WithEmoji(emoji.Font()))
img, report, err := c.Image(ctx, zuzu.WithEmoji(emoji.Font()))

The text measures with the font, and the PNG of Image draws with it. The SVG names its family for a text with an emoji, and a viewer draws it in the color font that it has. Without the font, an emoji draws nothing, as a character that no font has. A program that does not import text/emoji does not hold the font.

It is an option of Parse too, because some kinds of Mermaid, such as a sequence, a pie or a mindmap, lay out their labels when they compile (D38). The chart keeps the font, and each render of it that gives no font of its own uses the font. When both give a font, the font of the render wins.

func WithFont added in v0.10.0

func WithFont(f *text.Fallback) SharedOption

WithFont gives a parse or a render the font of the chart, such as IBM Plex Mono of the package text/mono (D35 part 11, D58 part 1):

font := zuzu.WithFont(mono.Font())
c, report, err := zuzu.Parse(src, font)
img, report, err := c.Image(ctx, font)

The chart measures each text in the font, with IBM Plex Sans for the characters that the font does not have, so the layout makes room for it. A font with several faces measures and draws each weight and style in its own face. Each text names the family of the font first, before IBM Plex Sans, over the font that the spec gives. The SVG embeds the font in a rule @font-face (D43), and the PNG of Image draws with it. A program that does not import the package of a font does not hold the font. It wins over a family of WithFonts and over the font that a scheme names, and the fonts of WithFonts draw the characters that it and IBM Plex Sans do not have (D62).

In a look drawn by hand, the font of WithLookFont wins over it. A look with no font of its own draws in the font of WithFont, and the report then gives no ErrNoLookFont.

It is an option of Parse too, as WithLookFont is, because some kinds of Mermaid lay out their labels when they compile. The chart keeps the font, and each render of it that gives no font uses the font. When both give a font, the font of the render wins, and such a kind lays out again in it at the render, so that each label fits its box (D62). A nil font gives no font.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/xo/zuzu"
	"github.com/xo/zuzu/text/mono"
)

func main() {
	ctx := context.Background()
	src := []byte(`sequenceDiagram
  Client->>Server: GET /chart
  Server-->>Client: 200 image/svg+xml`)
	font := zuzu.WithFont(mono.Font())
	chart, _, err := zuzu.Parse(src, font)
	if err != nil {
		log.Fatal(err)
	}
	var buf bytes.Buffer
	report, err := chart.SVG(ctx, &buf, font)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(strings.Contains(buf.String(), mono.Family), len(report))
}
Output:
true 0

func WithFonts added in v0.12.0

func WithFonts(fsys fs.FS) SharedOption

WithFonts gives a parse or a render a set of font files, such as the fonts of a folder or the fonts of the system that system.Fonts of the package text/system returns (D62):

fonts := zuzu.WithFonts(system.Fonts())
c, report, err := zuzu.Parse(src, fonts)
img, report, err := c.Image(ctx, fonts)

A text whose font names a family of the set, before IBM Plex Sans and before a generic family such as serif, draws in that family. The font of a text is the property font of its mark, or the font of a guide, such as labelFont of an axis. The layout measures the text in the family, the SVG names the family first and embeds its files in rules @font-face (D43), and the PNG of Image draws with it. A scheme can name a kind of font, such as theme.FontMono. A text that names no family of the set, or names IBM Plex Sans, draws in that kind when the set has its family. Another text draws as before, in IBM Plex Sans. The font of WithFont, or of a look drawn by hand, wins over all of these.

The fonts of the set also draw each character that IBM Plex Sans, the font of WithFont and the fonts of WithEmoji do not have. Such a character draws in the family of the first face of the set that has it, and the report no longer names it.

zuzu reads only the files of fsys, and no file of its own (hard rule 7). Each call of WithFonts makes a new set, which reads the table that names the faces of each file once, on its first use, and reads a whole file only when a text needs a family or a character of it. So a caller makes the option once and gives the same option to Parse and to each render, and the set reads the names once. When two faces have the same family, weight, style and width, the first file in the order of fs.WalkDir counts, as text.Set says, so the same files give the same output. The folders of system.Fonts come in the order of their names, so a font of the home folder comes before a font of the system.

The SVG embeds each font of the set that a text draws in as its family. A font of the set that draws only a character that the other fonts do not have is named in the font of the text, and the SVG embeds it only with WithEmbedCoverFonts.

It is an option of Parse too, because some kinds of Mermaid lay out their labels when they compile. The chart keeps the set, and each render of it that gives no set uses the set. When both give a set, the set of the render wins, and such a kind lays out again with it at the render (D62). A nil fsys gives no set.

func WithLayout added in v0.8.0

func WithLayout(name string) SharedOption

WithLayout forces a layout on each graph of the chart, by its name (D45 part 4): layered for zuzu.layered, dagre for zuzu.dagre, elk for the layered layout of ELK, or the name of another algorithm of ELK that Mermaid 12.3 has, such as elk.stress, elk.force, elk.mrtree, elk.sporeOverlap, elk.box or elk.rectpacking. A name of ELK needs the engine named elk of WithLayoutEngine, and another name that is not built in needs the engine of WithLayoutEngine with that name. The engine gets the name as graph.LayoutInput.Algorithm.

The option of the caller wins over the layout that the source asks for, as WithLook does. A forced layout with no engine is an issue, and an error in the strict mode, and the graph then lays out as though nothing forced it. The issue comes from the first graph that lays out, so a chart with no graph reports nothing.

It is an option of Parse too. The chart keeps the layout of Parse, and a render that forces no layout of its own lays out with it. The layout of the render wins over the layout of Parse, and an empty name in a render forces no layout, not even the layout of Parse.

func WithLayoutEngine added in v0.8.0

func WithLayoutEngine(e graph.Engine) SharedOption

WithLayoutEngine makes a layout engine available to zuzu, under its name (D45 part 3). It does not force the engine on a graph. A graph lays out with the engine when WithLayout or the spec names it, or when the source asks for its layout. The module github.com/xo/zuzu/elk gives the engine of ELK, named elk:

c, report, err := zuzu.Parse(src, zuzu.WithLayoutEngine(elk.Layout()))

A diagram of Mermaid that sets no layout, in a kind whose default layout in Mermaid 12.3 is ELK, then draws with ELK, and so does a diagram with layout: elk or a layout whose name starts with elk., such as elk.stress. Without the engine of ELK, such a diagram draws with zuzu.layered, with no issue (D32). The built in engines, graph.Layered and graph.Dagre, need no option.

It is an option of Parse too, as WithLook is. The chart keeps the engines of Parse, and a render can make more available. When the render and the parse each give an engine with the same name, the engine of the render wins. A nil engine makes nothing available.

func WithLook added in v0.8.0

func WithLook(l theme.Look) SharedOption

WithLook sets the look, such as theme.LookExcalidraw, which draws each mark as if by hand (D39, D40). It wins over the look that the spec asks for with zuzu.look in its config, such as look: handDrawn of a Mermaid diagram. A look that zuzu does not have is an issue, and draws in the standard look.

It is an option of Parse too, because some kinds of Mermaid lay out their labels when they compile, and a look measures its text in its own font (D40 part 1). The chart keeps the look, and each render of it that gives no look of its own uses the look. When both give a look, the look of the render wins.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/xo/zuzu"
	"github.com/xo/zuzu/text/excalifont"
	"github.com/xo/zuzu/theme"
)

func main() {
	ctx := context.Background()
	src := []byte(`flowchart TD
  A[Spec] --> B{Vega-Lite?}
  B -- yes --> C[Compile]
  B -- no --> D[Run]
  C --> D
  D --> E[(Scene)]`)
	look := zuzu.WithLook(theme.LookExcalidraw)
	font := zuzu.WithLookFont(theme.LookExcalidraw, excalifont.Font())
	chart, _, err := zuzu.Parse(src, look, font)
	if err != nil {
		log.Fatal(err)
	}
	var buf bytes.Buffer
	report, err := chart.SVG(ctx, &buf)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(strings.Contains(buf.String(), excalifont.Family), len(report))
}
Output:
true 0

func WithLookFont added in v0.8.0

func WithLookFont(l theme.Look, f *text.Fallback) SharedOption

WithLookFont gives a parse or a render the font of a look drawn by hand. The package text/excalifont gives the font of the look like Excalidraw, Excalifont:

font := zuzu.WithLookFont(theme.LookExcalidraw, excalifont.Font())
c, report, err := zuzu.Parse(src, font)
img, report, err := c.Image(ctx, zuzu.WithLook(theme.LookExcalidraw), font)

The look measures its text in the font, with IBM Plex Sans for the characters that the font does not have, so the layout makes room for it (D40 part 1). The SVG names its family first, and the PNG of Image draws with it. Without the font, the look draws its text in the font of WithFont, or else in the font that the scheme names and WithFonts gives, or else in IBM Plex Sans (D62). The report then warns of it with ErrNoLookFont, which names that font, in the strict mode too. A program that does not import text/excalifont does not hold the font. The standard look draws in IBM Plex Sans, and takes no font.

It is an option of Parse too, as WithLook is. The chart keeps the font, and each render of it that gives no font for the look uses the font. When both give a font, the font of the render wins.

func WithLookSeed added in v0.10.0

func WithLookSeed(seed int64) SharedOption

WithLookSeed sets the seed of a look drawn by hand, which picks the strokes of each shape (D40 part 6, D58 part 3). It wins over the seed that the spec asks for with zuzu.lookSeed in its config, such as handDrawnSeed of a Mermaid diagram. A seed of 0 is theme.SketchSeed. The standard look draws no strokes by hand, and the seed changes nothing in it.

It is an option of Parse too, as WithLook is. The chart keeps the seed, and each render of it that gives no seed of its own uses the seed. When both give a seed, the seed of the render wins.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"

	"github.com/xo/zuzu"
	"github.com/xo/zuzu/text/excalifont"
	"github.com/xo/zuzu/theme"
)

func main() {
	ctx := context.Background()
	src := []byte("flowchart LR\n  A[Spec] --> B[Scene]")
	look := zuzu.WithLook(theme.LookExcalidraw)
	font := zuzu.WithLookFont(theme.LookExcalidraw, excalifont.Font())
	chart, _, err := zuzu.Parse(src, look, font, zuzu.WithLookSeed(7))
	if err != nil {
		log.Fatal(err)
	}
	draw := func(opts ...zuzu.RenderOption) string {
		var buf bytes.Buffer
		if _, err := chart.SVG(ctx, &buf, opts...); err != nil {
			log.Fatal(err)
		}
		return buf.String()
	}
	fmt.Println(draw() == draw(zuzu.WithLookSeed(7)), draw() == draw(zuzu.WithLookSeed(8)))
}
Output:
true false

type View

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

View holds the state of one render. It is not safe for concurrent use.

func (*View) Data

func (v *View) Data(name string) ([]map[string]any, error)

Data returns the rows of a dataset of the top level, after its transforms.

func (*View) Scale

func (v *View) Scale(name string) (scale.Scale, error)

Scale returns a scale of the top level.

func (*View) Scene

func (v *View) Scene() *scene.Scene

Scene returns the scene graph of the view.

func (*View) Signal

func (v *View) Signal(name string) (any, error)

Signal returns the value of a signal of the top level.

Directories

Path Synopsis
Package dataflow reads the data of a Vega spec and runs its transforms (D6).
Package dataflow reads the data of a Vega spec and runs its transforms (D6).
Package expr parses and evaluates the expression language of Vega (D9).
Package expr parses and evaluates the expression language of Vega (D9).
Package format formats numbers and times with the syntax of d3-format and d3-time-format, which Vega uses for its axes, its legends and the functions format and timeFormat of its expressions.
Package format formats numbers and times with the syntax of d3-format and d3-time-format, which Vega uses for its axes, its legends and the functions format and timeFormat of its expressions.
Package geo holds the cartographic projections of zuzu and the geographic paths that they draw.
Package geo holds the cartographic projections of zuzu and the geographic paths that they draw.
Package graph holds the model of a diagram, a graph of nodes, edges and clusters, and its layered layout (D18, D31).
Package graph holds the model of a diagram, a graph of nodes, edges and clusters, and its layered layout (D18, D31).
dot
Package dot reads the DOT language of Graphviz into a graph (D31).
Package dot reads the DOT language of Graphviz into a graph (D31).
mermaid
Package mermaid reads diagrams of Mermaid 12.3.0 (D31): the flowchart, the swimlane diagram, the state diagram, the class diagram, the entity relationship diagram, the requirement diagram, the agentflow diagram and the use case diagram into a graph, and the charts into specs of Vega-Lite and Vega.
Package mermaid reads diagrams of Mermaid 12.3.0 (D31): the flowchart, the swimlane diagram, the state diagram, the class diagram, the entity relationship diagram, the requirement diagram, the agentflow diagram and the use case diagram into a graph, and the charts into specs of Vega-Lite and Vega.
Package icon reads icons in the JSON format of Iconify, and in SVG, for the nodes of a diagram (D31).
Package icon reads icons in the JSON format of Iconify, and in SVG, for the nodes of a diagram (D31).
icons
carbon
Package carbon bundles the icons of Carbon, the design system of IBM, version 11.92.0, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
Package carbon bundles the icons of Carbon, the design system of IBM, version 11.92.0, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
fa
Package fa bundles the solid icons of Font Awesome Free, version 7.3.1, under CC BY 4.0, as a pack of icons for the diagrams of zuzu (D31).
Package fa bundles the solid icons of Font Awesome Free, version 7.3.1, under CC BY 4.0, as a pack of icons for the diagrams of zuzu (D31).
k8s
Package k8s bundles the icons of Kubernetes, from the pack of Iconify of 2026-10-20, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
Package k8s bundles the icons of Kubernetes, from the pack of Iconify of 2026-10-20, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
mdi
Package mdi bundles Material Design Icons of Pictogrammers, from the pack of Iconify of 2025-01-21, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
Package mdi bundles Material Design Icons of Pictogrammers, from the pack of Iconify of 2025-01-21, under Apache-2.0, as a pack of icons for the diagrams of zuzu (D31).
internal
color
Package color reads the colors of CSS and converts them between the color spaces of d3: RGB, HSL, CIELAB and HCL.
Package color reads the colors of CSS and converts them between the color spaces of d3: RGB, HSL, CIELAB and HCL.
dagre
Package dagro lays out a directed graph in ranks, as dagre 3.1.1 does.
Package dagro lays out a directed graph in ranks, as dagre 3.1.1 does.
rough
Package rough draws lines, curves, shapes and their fills as if by hand.
Package rough draws lines, curves, shapes and their fills as if by hand.
shape
Package shape draws the geometry of the items of a scene as the path data of SVG: the curves of lines and areas, the symbols, the arcs, the trails and the rects with round corners.
Package shape draws the geometry of the items of a scene as the path data of SVG: the curves of lines and areas, the symbols, the arcs, the trails and the rects with round corners.
sketch
Package sketch turns a scene into the same scene drawn as if by hand, with the copy of rough-go in internal/rough (D39, D40).
Package sketch turns a scene into the same scene drawn as if by hand, with the copy of rough-go in internal/rough (D39, D40).
Package layout draws the guides of a chart in the look of zuzu: the axes, the legends and the titles (D12).
Package layout draws the guides of a chart in the look of zuzu: the axes, the legends and the titles (D12).
Package raster draws a scene graph as an image with the drawing of okage directly, without the round trip through SVG (D11).
Package raster draws a scene graph as an image with the drawing of okage directly, without the round trip through SVG (D11).
Package scale holds the scales of Vega, which map values of the data to values of a chart, such as positions and colors, and the ticks of each scale (D6).
Package scale holds the scales of Vega, which map values of the data to values of a chart, such as positions and colors, and the ticks of each scale (D6).
Package scene holds the scene graph of zuzu: the shapes of a chart with their final positions, sizes and colors (D8).
Package scene holds the scene graph of zuzu: the shapes of a chart with their final positions, sizes and colors (D8).
Package svg writes a scene graph as SVG (D10).
Package svg writes a scene graph as SVG (D10).
Package text measures text for the layout of zuzu (D11).
Package text measures text for the layout of zuzu (D11).
math
Package math gives STIX Two Math, a font of math under the SIL Open Font License 1.1, so that zuzu draws the math of KaTeX in a label of Mermaid (D36).
Package math gives STIX Two Math, a font of math under the SIL Open Font License 1.1, so that zuzu draws the math of KaTeX in a label of Mermaid (D36).
system
Package system returns the font folders of the platform as one file system, which a caller gives to zuzu.WithFonts (D62):
Package system returns the font folders of the platform as one file system, which a caller gives to zuzu.WithFonts (D62):
Package theme holds the themes of zuzu: a mode, light or dark, and a color scheme, which a caller swaps apart from the mode (D14).
Package theme holds the themes of zuzu: a mode, light or dark, and a color scheme, which a caller swaps apart from the mode (D14).
Package vega holds the Go types of a Vega spec, which it reads from JSON and writes back to JSON (D6, D21).
Package vega holds the Go types of a Vega spec, which it reads from JSON and writes back to JSON (D6, D21).
Package vegalite holds the Go types of a Vega-Lite spec and the compiler that turns it into a Vega spec (D6, D21).
Package vegalite holds the Go types of a Vega-Lite spec and the compiler that turns it into a Vega spec (D6, D21).

Jump to

Keyboard shortcuts

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