plot: Index | Examples | Files | Directories

package vg

import ""

Package vg defines an interface for drawing 2D vector graphics. This package is designed with the hope that many different vector graphics back-ends can conform to the interface.


// download font from debian
const url = ""

resp, err := http.Get(url)
if err != nil {
    log.Fatalf("could not download IPA font file: %+v", err)
defer resp.Body.Close()

ttf, err := untargz("IPAfont00303/ipam.ttf", resp.Body)
if err != nil {
    log.Fatalf("could not untar archive: %+v", err)

fontTTF, err := truetype.Parse(ttf)
if err != nil {
const fontName = "Mincho"
vg.AddFont(fontName, fontTTF)

plot.DefaultFont = fontName
plotter.DefaultFont = fontName

p, err := plot.New()
if err != nil {
    log.Fatalf("could not create plot: %+v", err)
p.Title.Text = "Hello, 世界"
p.X.Label.Text = "世"
p.Y.Label.Text = "界"

labels, err := plotter.NewLabels(
        XYs:    make(plotter.XYs, 1),
        Labels: []string{"こんにちは世界"},
if err != nil {
    log.Fatalf("could not create labels: %+v", err)

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


p, err := plot.New()
if err != nil {
    log.Fatalf("could not create plot: %+v", err)

p.Title.Text = "sin(x)"
p.X.Label.Text = "x"
p.Y.Label.Text = "f(x)"

p.X.Min = -2 * math.Pi
p.X.Max = +2 * math.Pi

fct := plotter.NewFunction(func(x float64) float64 {
    return math.Sin(x)
fct.Color = color.RGBA{R: 255, A: 255}

p.Add(fct, plotter.NewGrid())

c := vgimg.New(10*vg.Centimeter, 5*vg.Centimeter)

// Save image.
f, err := os.Create("testdata/sine.png")
if err != nil {
    log.Fatalf("could not create output image file: %+v", err)
defer f.Close()

err = png.Encode(f, c.Image())
if err != nil {
    log.Fatalf("could not encode image to PNG: %+v", err)

err = f.Close()
if err != nil {
    log.Fatalf("could not close output image file: %+v", err)


p, err := plot.New()
if err != nil {
    log.Fatalf("could not create plot: %+v", err)

p.Title.Text = "cos(x)"
p.X.Label.Text = "x"
p.Y.Label.Text = "f(x)"

p.X.Min = -2 * math.Pi
p.X.Max = +2 * math.Pi

fct := plotter.NewFunction(func(x float64) float64 {
    return math.Cos(x)
fct.Color = color.RGBA{B: 255, A: 255}

p.Add(fct, plotter.NewGrid())

c := vgimg.PngCanvas{
    Canvas: vgimg.New(10*vg.Centimeter, 5*vg.Centimeter),

// Save image.
f, err := os.Create("testdata/cosine.png")
if err != nil {
    log.Fatalf("could not create output image file: %+v", err)
defer f.Close()

_, err = c.WriteTo(f)
if err != nil {
    log.Fatalf("could not encode image to PNG: %+v", err)

err = f.Close()
if err != nil {
    log.Fatalf("could not close output image file: %+v", err)



Package Files

font.go font_syscall.go geom.go len.go tee.go vg.go


const (
    Inch       Length = 72
    Centimeter        = Inch / 2.54
    Millimeter        = Centimeter / 10

Common lengths.

const (
    MoveComp = iota

Constants that tag the type of each path component.


var FontDirs []string

FontDirs is a slice of directories searched for font data files. If the first font file found is unreadable or cannot be parsed, then subsequent directories are not tried, and the font will fail to load.

The default slice is initialised with the contents of the VGFONTPATH environment variable if it is defined. This slice may be changed to load fonts from different locations.

var (
    // FontMap maps Postscript/PDF font names to compatible
    // free fonts (TrueType converted ghostscript fonts).
    // Fonts that are not keys of this map are not supported.
    FontMap = map[string]string{

        "Courier":             "LiberationMono-Regular",
        "Courier-Bold":        "LiberationMono-Bold",
        "Courier-Oblique":     "LiberationMono-Italic",
        "Courier-BoldOblique": "LiberationMono-BoldItalic",

        "Helvetica":             "LiberationSans-Regular",
        "Helvetica-Bold":        "LiberationSans-Bold",
        "Helvetica-Oblique":     "LiberationSans-Italic",
        "Helvetica-BoldOblique": "LiberationSans-BoldItalic",

        "Times-Roman":      "LiberationSerif-Regular",
        "Times-Bold":       "LiberationSerif-Bold",
        "Times-Italic":     "LiberationSerif-Italic",
        "Times-BoldItalic": "LiberationSerif-BoldItalic",

func AddFont Uses

func AddFont(name string, font *truetype.Font)

AddFont associates a truetype.Font with the given name.

func Initialize Uses

func Initialize(c Canvas)

Initialize sets all of the canvas's values to their initial values.

type Canvas Uses

type Canvas interface {
    // SetLineWidth sets the width of stroked paths.
    // If the width is not positive then stroked lines
    // are not drawn.
    // The initial line width is 1 point.

    // SetLineDash sets the dash pattern for lines.
    // The pattern slice specifies the lengths of
    // alternating dashes and gaps, and the offset
    // specifies the distance into the dash pattern
    // to start the dash.
    // The initial dash pattern is a solid line.
    SetLineDash(pattern []Length, offset Length)

    // SetColor sets the current drawing color.
    // Note that fill color and stroke color are
    // the same, so if you want different fill
    // and stroke colors then you must set a color,
    // draw fills, set a new color and then draw lines.
    // The initial color is black.
    // If SetColor is called with a nil color then black is used.

    // Rotate applies a rotation transform to the context.
    // The parameter is specified in radians.
    Rotate(rad float64)

    // Translate applies a translational transform
    // to the context.
    Translate(pt Point)

    // Scale applies a scaling transform to the
    // context.
    Scale(x, y float64)

    // Push saves the current line width, the
    // current dash pattern, the current
    // transforms, and the current color
    // onto a stack so that the state can later
    // be restored by calling Pop().

    // Pop restores the context saved by the
    // corresponding call to Push().

    // Stroke strokes the given path.

    // Fill fills the given path.

    // FillString fills in text at the specified
    // location using the given font.
    // If the font size is zero, the text is not drawn.
    FillString(f Font, pt Point, text string)

    // DrawImage draws the image, scaled to fit
    // the destination rectangle.
    DrawImage(rect Rectangle, img image.Image)

A Canvas is the main drawing interface for 2D vector graphics. The origin is in the bottom left corner.

func MultiCanvas Uses

func MultiCanvas(cs ...Canvas) Canvas

MultiCanvas creates a canvas that duplicates its drawing operations to all the provided canvases, similar to the Unix tee(1) command.

Each drawing operation is sent to each listed canvas, one at a time.

type CanvasSizer Uses

type CanvasSizer interface {
    Size() (x, y Length)

CanvasSizer is a Canvas with a defined size.

type CanvasWriterTo Uses

type CanvasWriterTo interface {

CanvasWriterTo is a CanvasSizer with a WriteTo method.

type Font Uses

type Font struct {
    // Size is the size of the font.  The font size can
    // be used as a reasonable value for the vertical
    // distance between two successive lines of text.
    Size Length
    // contains filtered or unexported fields

A Font represents one of the supported font faces.

func MakeFont Uses

func MakeFont(name string, size Length) (font Font, err error)

MakeFont returns a font object. The name of the font must be a key of the FontMap. The font file is located by searching the FontDirs slice for a directory containing the relevant font file. The font file name is name mapped by FontMap with the .ttf extension. For example, the font file for the font name Courier is LiberationMono-Regular.ttf.

func (*Font) Extents Uses

func (f *Font) Extents() FontExtents

Extents returns the FontExtents for a font.

func (*Font) Font Uses

func (f *Font) Font() *truetype.Font

Font returns the corresponding truetype.Font.

func (*Font) FontFace Uses

func (f *Font) FontFace(dpi float64) font.Face

func (*Font) Name Uses

func (f *Font) Name() string

Name returns the name of the font.

func (*Font) SetName Uses

func (f *Font) SetName(name string) error

SetName sets the name of the font, effectively changing the font. If an error is returned then the font is left unchanged.

func (*Font) Width Uses

func (f *Font) Width(s string) Length

Width returns width of a string when drawn using the font.

type FontExtents Uses

type FontExtents struct {
    // Ascent is the distance that the text
    // extends above the baseline.
    Ascent Length

    // Descent is the distance that the text
    // extends below the baseline.  The descent
    // is given as a negative value.
    Descent Length

    // Height is the distance from the lowest
    // descending point to the highest ascending
    // point.
    Height Length

FontExtents contains font metric information.

type Length Uses

type Length float64

A Length is a unit-independent representation of length. Internally, the length is stored in postscript points.

func ParseLength Uses

func ParseLength(value string) (Length, error)

ParseLength parses a Length string. A Length string is a possible signed floating number with a unit. e.g. "42cm" "2.4in" "66pt" If no unit was given, ParseLength assumes it was (postscript) points. Currently valid units are:

mm (millimeter)
cm (centimeter)
in (inch)
pt (point)

func Points Uses

func Points(pt float64) Length

Points returns a length for the given number of points.

func (Length) Dots Uses

func (l Length) Dots(dpi float64) float64

Dots returns the length in dots for the given resolution.

func (Length) Points Uses

func (l Length) Points() float64

Points returns the length in postscript points.

type Path Uses

type Path []PathComp

func (*Path) Arc Uses

func (p *Path) Arc(pt Point, rad Length, s, a float64)

Arc adds an arc to the path defined by the center point of the arc's circle, the radius of the circle and the start and sweep angles.

func (*Path) Close Uses

func (p *Path) Close()

Close closes the path by connecting the current location to the start location with a line.

func (*Path) CubeTo Uses

func (p *Path) CubeTo(p1, p2, pt Point)

CubeTo adds a cubic curve element to the path, given by the control points p1 and p2 and the end point pt.

func (*Path) Line Uses

func (p *Path) Line(pt Point)

Line draws a line from the current point to the given point.

func (*Path) Move Uses

func (p *Path) Move(pt Point)

Move moves the current location of the path to the given point.

func (*Path) QuadTo Uses

func (p *Path) QuadTo(p1, pt Point)

QuadTo adds a quadratic curve element to the path, given by the control point p1 and end point pt.

type PathComp Uses

type PathComp struct {
    // Type is the type of a particluar component.
    // Based on the type, each of the following
    // fields may have a different meaning or may
    // be meaningless.
    Type int

    // The Pos field is used as the destination
    // of a MoveComp or LineComp and is the center
    // point of an ArcComp.  It is not used in
    // the CloseComp.
    Pos Point

    // Control is one or two intermediate points
    // for a CurveComp used by QuadTo and CubeTo.
    Control []Point

    // Radius is only used for ArcComps, it is
    // the radius of the circle defining the arc.
    Radius Length

    // Start and Angle are only used for ArcComps.
    // They define the start angle and sweep angle of
    // the arc around the circle.  The units of the
    // angle are radians.
    Start, Angle float64

A PathComp is a component of a path structure.

type Point Uses

type Point struct {
    X, Y Length

A Point is a location in 2d space.

Points are used for drawing, not for data. For data, see the XYer interface.

func (Point) Add Uses

func (p Point) Add(q Point) Point

Add returns the component-wise sum of two points.

func (Point) Dot Uses

func (p Point) Dot(q Point) Length

Dot returns the dot product of two points.

func (Point) Scale Uses

func (p Point) Scale(s Length) Point

Scale returns the component-wise product of a point and a scalar.

func (Point) Sub Uses

func (p Point) Sub(q Point) Point

Sub returns the component-wise difference of two points.

type Rectangle Uses

type Rectangle struct {
    Min Point
    Max Point

A Rectangle represents a rectangular region of 2d space.

func (Rectangle) Path Uses

func (r Rectangle) Path() (p Path)

Path returns the path of a Rect specified by its upper left corner, width and height.

func (Rectangle) Size Uses

func (r Rectangle) Size() Point

Size returns the width and height of a Rectangle.


fontsPackage fonts provides the Liberation fonts from
recorderPackage recorder provides support for vector graphics serialization.
vgepsPackage vgeps implements the vg.Canvas interface using encapsulated postscript.
vgimgPackage vgimg implements the vg.Canvas interface using as a backend to output raster images.
vgpdfPackage vgpdf implements the vg.Canvas interface using gofpdf (
vgsvgPackage vgsvg uses svgo ( as a backend for vg.
vgtexPackage vgtex provides a vg.Canvas implementation for LaTeX, targeted at the TikZ/PGF LaTeX package:

Package vg imports 14 packages (graph) and is imported by 134 packages. Updated 2020-06-02. Refresh now. Tools for package owners.