...

Package plot

import "gonum.org/v1/plot"
Overview
Index
Examples
Subdirectories

Overview ▾

Package plot provides an API for setting up plots, and primitives for drawing on plots.

Plot is the basic type for creating a plot, setting the title, axis labels, legend, tick marks, etc. Types implementing the Plotter interface can draw to the data area of a plot using the primitives made available by this package. Some standard implementations of the Plotter interface can be found in the gonum.org/v1/plot/plotter package which is documented here: https://godoc.org/gonum.org/v1/plot/plotter

Index ▾

Variables
func Align(plots [][]*Plot, t draw.Tiles, dc draw.Canvas) [][]draw.Canvas
func UnixTimeIn(loc *time.Location) func(t float64) time.Time
func Version() (version, sum string)
type Axis
    func (a Axis) Norm(x float64) float64
type ConstantTicks
    func (ts ConstantTicks) Ticks(float64, float64) []Tick
type DataRanger
type DefaultTicks
    func (DefaultTicks) Ticks(min, max float64) []Tick
type GlyphBox
type GlyphBoxer
type InvertedScale
    func (is InvertedScale) Normalize(min, max, x float64) float64
type Legend
    func NewLegend() Legend
    func (l *Legend) Add(name string, thumbs ...Thumbnailer)
    func (l *Legend) Draw(c draw.Canvas)
    func (l *Legend) Rectangle(c draw.Canvas) vg.Rectangle
type LinearScale
    func (LinearScale) Normalize(min, max, x float64) float64
type LogScale
    func (LogScale) Normalize(min, max, x float64) float64
type LogTicks
    func (t LogTicks) Ticks(min, max float64) []Tick
type Normalizer
type Plot
    func New() *Plot
    func (p *Plot) Add(ps ...Plotter)
    func (p *Plot) DataCanvas(da draw.Canvas) draw.Canvas
    func (p *Plot) Draw(c draw.Canvas)
    func (p *Plot) DrawGlyphBoxes(c draw.Canvas)
    func (p *Plot) GlyphBoxes(*Plot) (boxes []GlyphBox)
    func (p *Plot) HideAxes()
    func (p *Plot) HideX()
    func (p *Plot) HideY()
    func (p *Plot) NominalX(names ...string)
    func (p *Plot) NominalY(names ...string)
    func (p *Plot) Save(w, h vg.Length, file string) (err error)
    func (p *Plot) Transforms(c *draw.Canvas) (x, y func(float64) vg.Length)
    func (p *Plot) WriterTo(w, h vg.Length, format string) (io.WriterTo, error)
type Plotter
type Thumbnailer
type Tick
    func (t Tick) IsMinor() bool
type Ticker
type TickerFunc
    func (f TickerFunc) Ticks(min, max float64) []Tick
type TimeTicks
    func (t TimeTicks) Ticks(min, max float64) []Tick

Package files

align.go axis.go doc.go labelling.go legend.go plot.go version.go vgall.go

Variables

var (
    // DefaultFont is the name of the default font for plot text.
    DefaultFont = font.Font{
        Typeface: "Liberation",
        Variant:  "Serif",
    }

    // DefaultTextHandler is the default text handler used for text processing.
    DefaultTextHandler text.Handler
)

UTCUnixTime is the default time conversion for TimeTicks.

var UTCUnixTime = UnixTimeIn(time.UTC)

func Align

func Align(plots [][]*Plot, t draw.Tiles, dc draw.Canvas) [][]draw.Canvas

Align returns a two-dimensional row-major array of Canvases which will produce tiled plots with DataCanvases that are evenly sized and spaced. The arguments to the function are a two-dimensional row-major array of plots, a tile configuration, and the canvas to which the tiled plots are to be drawn.

Example

Code:

const rows, cols = 4, 3
plots := make([][]*plot.Plot, rows)
for j := 0; j < rows; j++ {
    plots[j] = make([]*plot.Plot, cols)
    for i := 0; i < cols; i++ {
        if i == 0 && j == 2 {
            // This shows what happens when there are nil plots.
            continue
        }

        p := plot.New()

        if j == 0 && i == 2 {
            // This shows what happens when the axis padding
            // is different among plots.
            p.X.Padding, p.Y.Padding = 0, 0
        }

        if j == 1 && i == 1 {
            // To test the Align function, we make the axis labels
            // on one of the plots stick out.
            p.Y.Max = 1e9
            p.X.Max = 1e9
            p.X.Tick.Label.Rotation = math.Pi / 2
            p.X.Tick.Label.XAlign = draw.XRight
            p.X.Tick.Label.YAlign = draw.YCenter
            p.X.Tick.Label.Font.Size = 8
            p.Y.Tick.Label.Font.Size = 8
        } else {
            p.Y.Max = 1e9
            p.X.Max = 1e9
            p.X.Tick.Label.Font.Size = 1
            p.Y.Tick.Label.Font.Size = 1
        }

        plots[j][i] = p
    }
}

img := vgimg.New(vg.Points(150), vg.Points(175))
dc := draw.New(img)

t := draw.Tiles{
    Rows:      rows,
    Cols:      cols,
    PadX:      vg.Millimeter,
    PadY:      vg.Millimeter,
    PadTop:    vg.Points(2),
    PadBottom: vg.Points(2),
    PadLeft:   vg.Points(2),
    PadRight:  vg.Points(2),
}

canvases := plot.Align(plots, t, dc)
for j := 0; j < rows; j++ {
    for i := 0; i < cols; i++ {
        if plots[j][i] != nil {
            plots[j][i].Draw(canvases[j][i])
        }
    }
}

w, err := os.Create("testdata/align.png")
if err != nil {
    panic(err)
}
defer w.Close()
png := vgimg.PngCanvas{Canvas: img}
if _, err := png.WriteTo(w); err != nil {
    panic(err)
}

func UnixTimeIn

func UnixTimeIn(loc *time.Location) func(t float64) time.Time

UnixTimeIn returns a time conversion function for the given location.

func Version

func Version() (version, sum string)

Version returns the version of Gonum/plot and its checksum. The returned values are only valid in binaries built with module support.

If a replace directive exists in the Gonum/plot go.mod, the replace will be reported in the version in the following format:

"version=>[replace-path] [replace-version]"

and the replace sum will be returned in place of the original sum.

The exact version format returned by Version may change in future.

type Axis

An Axis represents either a horizontal or vertical axis of a plot.

type Axis struct {
    // Min and Max are the minimum and maximum data
    // values represented by the axis.
    Min, Max float64

    Label struct {
        // Text is the axis label string.
        Text string

        // Padding is the distance between the label and the axis.
        Padding vg.Length

        // TextStyle is the style of the axis label text.
        // For the vertical axis, one quarter turn
        // counterclockwise will be added to the label
        // text before drawing.
        TextStyle text.Style

        // Position is where the axis label string should be drawn.
        // The default value is draw.PosCenter, displaying the label
        // at the center of the axis.
        // Valid values are [-1,+1], with +1 being the far right/top
        // of the axis, and -1 the far left/bottom of the axis.
        Position float64
    }

    // LineStyle is the style of the axis line.
    draw.LineStyle

    // Padding between the axis line and the data.  Having
    // non-zero padding ensures that the data is never drawn
    // on the axis, thus making it easier to see.
    Padding vg.Length

    Tick struct {
        // Label is the TextStyle on the tick labels.
        Label text.Style

        // LineStyle is the LineStyle of the tick lines.
        draw.LineStyle

        // Length is the length of a major tick mark.
        // Minor tick marks are half of the length of major
        // tick marks.
        Length vg.Length

        // Marker returns the tick marks.  Any tick marks
        // returned by the Marker function that are not in
        // range of the axis are not drawn.
        Marker Ticker
    }

    // Scale transforms a value given in the data coordinate system
    // to the normalized coordinate system of the axis—its distance
    // along the axis as a fraction of the axis range.
    Scale Normalizer

    // AutoRescale enables an axis to automatically adapt its minimum
    // and maximum boundaries, according to its underlying Ticker.
    AutoRescale bool
}

Example (LabelsPosition)

Code:

p := plot.New()
p.Title.Text = "Title"
p.X.Label.Text = "X [mm]"
p.Y.Label.Text = "Y [A.U.]"
p.X.Label.Position = draw.PosRight
p.Y.Label.Position = draw.PosTop
p.X.Min = -10
p.X.Max = +10
p.Y.Min = -10
p.Y.Max = +10

err := p.Save(10*vg.Centimeter, 10*vg.Centimeter, "testdata/axis_labels.png")
if err != nil {
    log.Fatalf("could not save plot: %+v", err)
}

func (Axis) Norm

func (a Axis) Norm(x float64) float64

Norm returns the value of x, given in the data coordinate system, normalized to its distance as a fraction of the range of this axis. For example, if x is a.Min then the return value is 0, and if x is a.Max then the return value is 1.

type ConstantTicks

ConstantTicks is suitable for the Tick.Marker field of an Axis. This function returns the given set of ticks.

type ConstantTicks []Tick

func (ConstantTicks) Ticks

func (ts ConstantTicks) Ticks(float64, float64) []Tick

Ticks returns Ticks in a specified range

type DataRanger

DataRanger wraps the DataRange method.

type DataRanger interface {
    // DataRange returns the range of X and Y values.
    DataRange() (xmin, xmax, ymin, ymax float64)
}

type DefaultTicks

DefaultTicks is suitable for the Tick.Marker field of an Axis, it returns a reasonable default set of tick marks.

type DefaultTicks struct{}

func (DefaultTicks) Ticks

func (DefaultTicks) Ticks(min, max float64) []Tick

Ticks returns Ticks in the specified range.

type GlyphBox

A GlyphBox describes the location of a glyph and the offset/size of its bounding box.

If the Rectangle.Size().X is non-positive (<= 0) then the GlyphBox is ignored when computing the horizontal padding, and likewise with Rectangle.Size().Y and the vertical padding.

type GlyphBox struct {
    // The glyph location in normalized coordinates.
    X, Y float64

    // Rectangle is the offset of the glyph's minimum drawing
    // point relative to the glyph location and its size.
    vg.Rectangle
}

type GlyphBoxer

GlyphBoxer wraps the GlyphBoxes method. It should be implemented by things that meet the Plotter interface that draw glyphs so that their glyphs are not clipped if drawn near the edge of the draw.Canvas.

When computing padding, the plot ignores GlyphBoxes as follows: If the Size.X > 0 and the X value is not in range of the X axis then the box is ignored. If Size.Y > 0 and the Y value is not in range of the Y axis then the box is ignored.

Also, GlyphBoxes with Size.X <= 0 are ignored when computing horizontal padding and GlyphBoxes with Size.Y <= 0 are ignored when computing vertical padding. This is useful for things like box plots and bar charts where the boxes and bars are considered to be glyphs in the X direction (and thus need padding), but may be clipped in the Y direction (and do not need padding).

type GlyphBoxer interface {
    GlyphBoxes(*Plot) []GlyphBox
}

type InvertedScale

InvertedScale can be used as the value of an Axis.Scale function to invert the axis using any Normalizer.

type InvertedScale struct{ Normalizer }

func (InvertedScale) Normalize

func (is InvertedScale) Normalize(min, max, x float64) float64

Normalize returns a normalized [0, 1] value for the position of x.

type Legend

A Legend gives a description of the meaning of different data elements of the plot. Each legend entry has a name and a thumbnail, where the thumbnail shows a small sample of the display style of the corresponding data.

type Legend struct {
    // TextStyle is the style given to the legend
    // entry texts.
    TextStyle text.Style

    // Padding is the amount of padding to add
    // between each entry in the legend.  If Padding
    // is zero then entries are spaced based on the
    // font size.
    Padding vg.Length

    // Top and Left specify the location of the legend.
    // If Top is true the legend is located along the top
    // edge of the plot, otherwise it is located along
    // the bottom edge.  If Left is true then the legend
    // is located along the left edge of the plot, and the
    // text is positioned after the icons, otherwise it is
    // located along the right edge and the text is
    // positioned before the icons.
    Top, Left bool

    // XOffs and YOffs are added to the legend's
    // final position.
    XOffs, YOffs vg.Length

    // YPosition specifies the vertical position of a legend entry.
    // Valid values are [-1,+1], with +1 being the top of the
    // entry vertical space, and -1 the bottom.
    YPosition float64

    // ThumbnailWidth is the width of legend thumbnails.
    ThumbnailWidth vg.Length
    // contains filtered or unexported fields
}

Example (Standalone)

This example creates a some standalone legends with borders around them.

Code:

package plot_test

import (
    "image/color"
    "os"

    "gonum.org/v1/plot"
    "gonum.org/v1/plot/vg"
    "gonum.org/v1/plot/vg/draw"
    "gonum.org/v1/plot/vg/vgimg"
)

type exampleThumbnailer struct {
    color.Color
}

// Thumbnail fulfills the plot.Thumbnailer interface.
func (et exampleThumbnailer) Thumbnail(c *draw.Canvas) {
    pts := []vg.Point{
        {X: c.Min.X, Y: c.Min.Y},
        {X: c.Min.X, Y: c.Max.Y},
        {X: c.Max.X, Y: c.Max.Y},
        {X: c.Max.X, Y: c.Min.Y},
    }
    poly := c.ClipPolygonY(pts)
    c.FillPolygon(et.Color, poly)

    pts = append(pts, vg.Point{X: c.Min.X, Y: c.Min.Y})
    outline := c.ClipLinesY(pts)
    c.StrokeLines(draw.LineStyle{
        Color: color.Black,
        Width: vg.Points(1),
    }, outline...)
}

// This example creates a some standalone legends with borders around them.
func ExampleLegend_standalone() {
    c := vgimg.New(vg.Points(120), vg.Points(100))
    dc := draw.New(c)

    // These example thumbnailers could be replaced with any of Plotters
    // in the plotter subpackage.
    red := exampleThumbnailer{Color: color.NRGBA{R: 255, A: 255}}
    green := exampleThumbnailer{Color: color.NRGBA{G: 255, A: 255}}
    blue := exampleThumbnailer{Color: color.NRGBA{B: 255, A: 255}}

    l := plot.NewLegend()
    l.Add("red", red)
    l.Add("green", green)
    l.Add("blue", blue)
    l.Padding = vg.Millimeter
    l.YPosition = draw.PosCenter

    // purpleRectangle draws a purple rectangle around the given Legend.
    purpleRectangle := func(l plot.Legend) {
        r := l.Rectangle(dc)
        dc.StrokeLines(draw.LineStyle{
            Color: color.NRGBA{R: 255, B: 255, A: 255},
            Width: vg.Points(1),
        }, []vg.Point{
            {X: r.Min.X, Y: r.Min.Y}, {X: r.Min.X, Y: r.Max.Y}, {X: r.Max.X, Y: r.Max.Y},
            {X: r.Max.X, Y: r.Min.Y}, {X: r.Min.X, Y: r.Min.Y},
        })
    }

    l.Draw(dc)
    purpleRectangle(l)

    l.Left = true
    l.Draw(dc)
    purpleRectangle(l)

    l.Top = true
    l.Draw(dc)
    purpleRectangle(l)

    l.Left = false
    l.Draw(dc)
    purpleRectangle(l)

    w, err := os.Create("testdata/legend_standalone.png")
    if err != nil {
        panic(err)
    }
    defer w.Close()

    png := vgimg.PngCanvas{Canvas: c}
    if _, err := png.WriteTo(w); err != nil {
        panic(err)
    }
}

func NewLegend

func NewLegend() Legend

NewLegend returns a legend with the default parameter settings.

func (*Legend) Add

func (l *Legend) Add(name string, thumbs ...Thumbnailer)

Add adds an entry to the legend with the given name. The entry's thumbnail is drawn as the composite of all of the thumbnails.

func (*Legend) Draw

func (l *Legend) Draw(c draw.Canvas)

Draw draws the legend to the given draw.Canvas.

func (*Legend) Rectangle

func (l *Legend) Rectangle(c draw.Canvas) vg.Rectangle

Rectangle returns the extent of the Legend.

type LinearScale

LinearScale an be used as the value of an Axis.Scale function to set the axis to a standard linear scale.

type LinearScale struct{}

func (LinearScale) Normalize

func (LinearScale) Normalize(min, max, x float64) float64

Normalize returns the fractional distance of x between min and max.

type LogScale

LogScale can be used as the value of an Axis.Scale function to set the axis to a log scale.

type LogScale struct{}

func (LogScale) Normalize

func (LogScale) Normalize(min, max, x float64) float64

Normalize returns the fractional logarithmic distance of x between min and max.

type LogTicks

LogTicks is suitable for the Tick.Marker field of an Axis, it returns tick marks suitable for a log-scale axis.

type LogTicks struct {
    // Prec specifies the precision of tick rendering
    // according to the documentation for strconv.FormatFloat.
    Prec int
}

func (LogTicks) Ticks

func (t LogTicks) Ticks(min, max float64) []Tick

Ticks returns Ticks in a specified range

type Normalizer

Normalizer rescales values from the data coordinate system to the normalized coordinate system.

type Normalizer interface {
    // Normalize transforms a value x in the data coordinate system to
    // the normalized coordinate system.
    Normalize(min, max, x float64) float64
}

type Plot

Plot is the basic type representing a plot.

type Plot struct {
    Title struct {
        // Text is the text of the plot title.  If
        // Text is the empty string then the plot
        // will not have a title.
        Text string

        // Padding is the amount of padding
        // between the bottom of the title and
        // the top of the plot.
        Padding vg.Length

        // TextStyle specifies how the plot title text should be displayed.
        TextStyle text.Style
    }

    // BackgroundColor is the background color of the plot.
    // The default is White.
    BackgroundColor color.Color

    // X and Y are the horizontal and vertical axes
    // of the plot respectively.
    X, Y Axis

    // Legend is the plot's legend.
    Legend Legend

    // TextHandler parses and formats text according to a given
    // dialect (Markdown, LaTeX, plain, ...)
    // The default is a plain text handler.
    TextHandler text.Handler
    // contains filtered or unexported fields
}

func New

func New() *Plot

New returns a new plot with some reasonable default settings.

func (*Plot) Add

func (p *Plot) Add(ps ...Plotter)

Add adds a Plotters to the plot.

If the plotters implements DataRanger then the minimum and maximum values of the X and Y axes are changed if necessary to fit the range of the data.

When drawing the plot, Plotters are drawn in the order in which they were added to the plot.

func (*Plot) DataCanvas

func (p *Plot) DataCanvas(da draw.Canvas) draw.Canvas

DataCanvas returns a new draw.Canvas that is the subset of the given draw area into which the plot data will be drawn.

func (*Plot) Draw

func (p *Plot) Draw(c draw.Canvas)

Draw draws a plot to a draw.Canvas.

Plotters are drawn in the order in which they were added to the plot. Plotters that implement the GlyphBoxer interface will have their GlyphBoxes taken into account when padding the plot so that none of their glyphs are clipped.

func (*Plot) DrawGlyphBoxes

func (p *Plot) DrawGlyphBoxes(c draw.Canvas)

DrawGlyphBoxes draws red outlines around the plot's GlyphBoxes. This is intended for debugging.

func (*Plot) GlyphBoxes

func (p *Plot) GlyphBoxes(*Plot) (boxes []GlyphBox)

GlyphBoxes returns the GlyphBoxes for all plot data that meet the GlyphBoxer interface.

func (*Plot) HideAxes

func (p *Plot) HideAxes()

HideAxes hides the X and Y axes.

func (*Plot) HideX

func (p *Plot) HideX()

HideX configures the X axis so that it will not be drawn.

func (*Plot) HideY

func (p *Plot) HideY()

HideY configures the Y axis so that it will not be drawn.

func (*Plot) NominalX

func (p *Plot) NominalX(names ...string)

NominalX configures the plot to have a nominal X axis—an X axis with names instead of numbers. The X location corresponding to each name are the integers, e.g., the x value 0 is centered above the first name and 1 is above the second name, etc. Labels for x values that do not end up in range of the X axis will not have tick marks.

func (*Plot) NominalY

func (p *Plot) NominalY(names ...string)

NominalY is like NominalX, but for the Y axis.

func (*Plot) Save

func (p *Plot) Save(w, h vg.Length, file string) (err error)

Save saves the plot to an image file. The file format is determined by the extension.

Supported extensions are:

func (*Plot) Transforms

func (p *Plot) Transforms(c *draw.Canvas) (x, y func(float64) vg.Length)

Transforms returns functions to transfrom from the x and y data coordinate system to the draw coordinate system of the given draw area.

func (*Plot) WriterTo

func (p *Plot) WriterTo(w, h vg.Length, format string) (io.WriterTo, error)

WriterTo returns an io.WriterTo that will write the plot as the specified image format.

Supported formats are:

type Plotter

Plotter is an interface that wraps the Plot method. Some standard implementations of Plotter can be found in the gonum.org/v1/plot/plotter package, documented here: https://godoc.org/gonum.org/v1/plot/plotter

type Plotter interface {
    // Plot draws the data to a draw.Canvas.
    Plot(draw.Canvas, *Plot)
}

type Thumbnailer

Thumbnailer wraps the Thumbnail method, which draws the small image in a legend representing the style of data.

type Thumbnailer interface {
    // Thumbnail draws an thumbnail representing
    // a legend entry.  The thumbnail will usually show
    // a smaller representation of the style used
    // to plot the corresponding data.
    Thumbnail(c *draw.Canvas)
}

type Tick

A Tick is a single tick mark on an axis.

type Tick struct {
    // Value is the data value marked by this Tick.
    Value float64

    // Label is the text to display at the tick mark.
    // If Label is an empty string then this is a minor
    // tick mark.
    Label string
}

func (Tick) IsMinor

func (t Tick) IsMinor() bool

IsMinor returns true if this is a minor tick mark.

type Ticker

Ticker creates Ticks in a specified range

type Ticker interface {
    // Ticks returns Ticks in a specified range
    Ticks(min, max float64) []Tick
}

type TickerFunc

TickerFunc is suitable for the Tick.Marker field of an Axis. It is an adapter which allows to quickly setup a Ticker using a function with an appropriate signature.

type TickerFunc func(min, max float64) []Tick

func (TickerFunc) Ticks

func (f TickerFunc) Ticks(min, max float64) []Tick

Ticks implements plot.Ticker.

type TimeTicks

TimeTicks is suitable for axes representing time values.

type TimeTicks struct {
    // Ticker is used to generate a set of ticks.
    // If nil, DefaultTicks will be used.
    Ticker Ticker

    // Format is the textual representation of the time value.
    // If empty, time.RFC3339 will be used
    Format string

    // Time takes a float64 value and converts it into a time.Time.
    // If nil, UTCUnixTime is used.
    Time func(t float64) time.Time
}

func (TimeTicks) Ticks

func (t TimeTicks) Ticks(min, max float64) []Tick

Ticks implements plot.Ticker.

Subdirectories

Name Synopsis
..
cmpimg Package cmpimg compares the raw representation of images taking into account idiosyncracies related to their underlying format (SVG, PDF, PNG, ...).
font Package font provides types to describe and select text font faces.
liberation Package liberation exports the Liberation fonts as a font.Collection.
gob
palette Package palette provides basic color palette handling.
brewer Package brewer provides Brewer Palettes for informative graphics.
moreland Package moreland provides color maps for pseudocoloring scalar fields.
plotter Package plotter defines a variety of standard Plotters for the plot package.
plotutil Package plotutil contains a small number of utilites for creating plots.
text Package text provides types and functions to parse, format and render text.
tools
bezier Package bezier implements 2D Bézier curve calculation.
vg Package vg defines an interface for drawing 2D vector graphics.
draw Package draw provides types and functions to draw shapes on a vg.Canvas.
recorder Package recorder provides support for vector graphics serialization.
vgeps Package vgeps implements the vg.Canvas interface using encapsulated postscript.
vggio Package vggio provides a vg.Canvas implementation backed by Gio, a toolkit that implements portable immediate GUI mode in Go.
vgimg Package vgimg implements the vg.Canvas interface using git.sr.ht/~sbinet/gg as a backend to output raster images.
vgpdf Package vgpdf implements the vg.Canvas interface using gofpdf (github.com/phpdave11/gofpdf).
vgsvg Package vgsvg uses svgo (github.com/ajstarks/svgo) as a backend for vg.
vgtex Package vgtex provides a vg.Canvas implementation for LaTeX, targeted at the TikZ/PGF LaTeX package: https://sourceforge.net/projects/pgf