All formats

gonum/plot

LanguageGo
LicenseBSD-3-Clause
Repositorygithub.com/gonum/plot
Documentationpkg.go.dev/gonum.org/v1/plot, vgeps
Depends onpure Go
Read / writeno / yes (EPS)

gonum/plot is the plotting library of the Gonum numeric project. You build a plot.Plot from plotters (lines, scatter points, bars, histograms, box plots, heat maps) and save it; Save picks the output from the extension, and .eps uses the vgeps backend. The EPS file has a %%BoundingBox equal to the plot size, so it drops straight into LaTeX documents.

It only writes EPS. The output has no preview image.

Installation#

Shell
go get gonum.org/v1/plot@latest

Basic usage: save a line plot as EPS#

Go
package main

import (
	"log"
	"math"

	"gonum.org/v1/plot"
	"gonum.org/v1/plot/plotter"
	"gonum.org/v1/plot/vg"
)

func main() {
	pts := make(plotter.XYs, 100)
	for i := range pts {
		x := float64(i) / 10
		pts[i].X = x
		pts[i].Y = math.Sin(x)
	}

	p := plot.New()
	p.Title.Text = "sin(x)"
	p.X.Label.Text = "x"
	p.Y.Label.Text = "y"
	p.Add(plotter.NewGrid())

	line, err := plotter.NewLine(pts)
	if err != nil {
		log.Fatal(err)
	}
	p.Add(line)

	// 4 x 3 inches; the extension selects EPS
	if err := p.Save(4*vg.Inch, 3*vg.Inch, "sin.eps"); err != nil {
		log.Fatal(err)
	}
}

How to write EPS to an io.Writer#

WriterTo renders to any format without a file:

Go
wt, err := p.WriterTo(4*vg.Inch, 3*vg.Inch, "eps")
if err != nil {
	log.Fatal(err)
}
var buf bytes.Buffer
if _, err := wt.WriteTo(&buf); err != nil {
	log.Fatal(err)
}

How to set the EPS title and draw on the canvas yourself#

vgeps.NewTitle writes a %%Title comment. Draw the plot onto it with draw.New:

Go
import (
	"os"

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

c := vgeps.NewTitle(6*vg.Centimeter, 4*vg.Centimeter, "Measurements")
p.Draw(draw.New(c))

f, err := os.Create("measurements.eps")
if err != nil {
	log.Fatal(err)
}
defer f.Close()
if _, err := c.WriteTo(f); err != nil {
	log.Fatal(err)
}

How to save the same plot as EPS and PDF#

Go
for _, name := range []string{"plot.eps", "plot.pdf", "plot.svg"} {
	if err := p.Save(10*vg.Centimeter, 7*vg.Centimeter, name); err != nil {
		log.Fatal(err)
	}
}

Tips#