plot: gonum.org/v1/plot Index | Examples | Files | Directories

package plot

import "gonum.org/v1/plot"

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

Examples

Package Files

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

Variables

var (
    // DefaultFont is the name of the default font for plot text.
    DefaultFont = "Times-Roman"
)
var UTCUnixTime = UnixTimeIn(time.UTC)

UTCUnixTime is the default time conversion for TimeTicks.

func Align Uses

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.

Code:

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

        p, err := New()
        if err != nil {
            panic(err)
        }

        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 := 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)
}

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

func UnixTimeIn Uses

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

UnixTimeIn returns a time conversion function for the given location.

type Axis Uses

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

        // 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.
        draw.TextStyle
    }

    // 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 draw.TextStyle

        // 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
}

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

func (Axis) Norm Uses

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 Uses

type ConstantTicks []Tick

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

func (ConstantTicks) Ticks Uses

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

Ticks returns Ticks in a specified range

type DataRanger Uses

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

DataRanger wraps the DataRange method.

type DefaultTicks Uses

type DefaultTicks struct{}

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

func (DefaultTicks) Ticks Uses

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

Ticks returns Ticks in the specified range.

type GlyphBox Uses

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
}

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 GlyphBoxer Uses

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

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 InvertedScale Uses

type InvertedScale struct{ Normalizer }

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

func (InvertedScale) Normalize Uses

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

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

type Legend Uses

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

    // 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

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

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.

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

Code:

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, err := NewLegend()
if err != nil {
    panic(err)
}
l.Add("red", red)
l.Add("green", green)
l.Add("blue", blue)
l.Padding = vg.Millimeter

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

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

func NewLegend Uses

func NewLegend() (Legend, error)

NewLegend returns a legend with the default parameter settings.

func (*Legend) Add Uses

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 Uses

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

Draw draws the legend to the given draw.Canvas.

func (*Legend) Rectangle Uses

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

Rectangle returns the extent of the Legend.

type LinearScale Uses

type LinearScale struct{}

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

func (LinearScale) Normalize Uses

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

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

type LogScale Uses

type LogScale struct{}

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

func (LogScale) Normalize Uses

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

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

type LogTicks Uses

type LogTicks struct{}

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

func (LogTicks) Ticks Uses

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

Ticks returns Ticks in a specified range

type Normalizer Uses

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

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

type Plot Uses

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

        draw.TextStyle
    }

    // 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
    // contains filtered or unexported fields
}

Plot is the basic type representing a plot.

func New Uses

func New() (*Plot, error)

New returns a new plot with some reasonable default settings.

func (*Plot) Add Uses

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 Uses

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 Uses

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 Uses

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

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

func (*Plot) GlyphBoxes Uses

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

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

func (*Plot) HideAxes Uses

func (p *Plot) HideAxes()

HideAxes hides the X and Y axes.

func (*Plot) HideX Uses

func (p *Plot) HideX()

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

func (*Plot) HideY Uses

func (p *Plot) HideY()

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

func (*Plot) NominalX Uses

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 Uses

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

NominalY is like NominalX, but for the Y axis.

func (*Plot) Save Uses

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:

.eps, .jpg, .jpeg, .pdf, .png, .svg, .tif and .tiff.

func (*Plot) Transforms Uses

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 Uses

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:

eps, jpg|jpeg, pdf, png, svg, and tif|tiff.

type Plotter Uses

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

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 Thumbnailer Uses

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)
}

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

type Tick Uses

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
}

A Tick is a single tick mark on an axis.

func (Tick) IsMinor Uses

func (t Tick) IsMinor() bool

IsMinor returns true if this is a minor tick mark.

type Ticker Uses

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

Ticker creates Ticks in a specified range

type TickerFunc Uses

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

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.

func (TickerFunc) Ticks Uses

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

Ticks implements plot.Ticker.

type TimeTicks Uses

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
}

TimeTicks is suitable for axes representing time values.

func (TimeTicks) Ticks Uses

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

Ticks implements plot.Ticker.

Directories

PathSynopsis
gob
internal/cmpimgPackage cmpimg compares the raw representation of images taking into account idiosyncracies related to their underlying format (SVG, PDF, PNG, ...).
palettePackage palette provides basic color palette handling.
palette/brewerPackage brewer provides Brewer Palettes for informative graphics.
palette/morelandPackage moreland provides color maps for pseudocoloring scalar fields.
plotterPackage plotter defines a variety of standard Plotters for the plot package.
plotutilPackage plotutil contains a small number of utilites for creating plots.
tools/bezierPackage bezier implements 2D Bézier curve calculation.
vgPackage vg defines an interface for drawing 2D vector graphics.
vg/draw
vg/fontsPackage fonts provides the Liberation fonts from https://fedorahosted.org/liberation-fonts/
vg/recorderPackage recorder provides support for vector graphics serialization.
vg/vgepsPackage vgeps implements the vg.Canvas interface using encapsulated postscript.
vg/vgimgPackage vgimg implements the vg.Canvas interface using draw2d (github.com/llgcode/draw2d) as a backend to output raster images.
vg/vgpdfPackage vgpdf implements the vg.Canvas interface using gofpdf (github.com/jung-kurt/gofpdf).
vg/vgsvgPackage vgsvg uses svgo (github.com/ajstarks/svgo) as a backend for vg.
vg/vgtexPackage vgtex provides a vg.Canvas implementation for LaTeX, targeted at the TikZ/PGF LaTeX package: https://sourceforge.net/projects/pgf

Package plot imports 11 packages (graph) and is imported by 67 packages. Updated 2019-01-19. Refresh now. Tools for package owners.