Ejemplo n.º 1
0
// Example_functions draws some functions.
func Example_functions() *plot.Plot {
	p, err := plot.New()
	if err != nil {
		panic(err)
	}
	p.Title.Text = "Functions"
	p.X.Label.Text = "X"
	p.Y.Label.Text = "Y"

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

	exp := plotter.NewFunction(func(x float64) float64 { return math.Pow(2, x) })
	exp.Dashes = []vg.Length{vg.Points(2), vg.Points(2)}
	exp.Width = vg.Points(2)
	exp.Color = color.RGBA{G: 255, A: 255}

	sin := plotter.NewFunction(func(x float64) float64 { return 10*math.Sin(x) + 50 })
	sin.Dashes = []vg.Length{vg.Points(4), vg.Points(5)}
	sin.Width = vg.Points(4)
	sin.Color = color.RGBA{R: 255, A: 255}

	p.Add(quad, exp, sin)
	p.Legend.Add("x^2", quad)
	p.Legend.Add("2^x", exp)
	p.Legend.Add("10*sin(x)+50", sin)
	p.Legend.ThumbnailWidth = vg.Inches(0.5)

	p.X.Min = 0
	p.X.Max = 10
	p.Y.Min = 0
	p.Y.Max = 100
	return p
}
Ejemplo n.º 2
0
// NewImage returns a new image canvas
// that draws to the given image.  The
// minimum point of the given image
// should probably be 0,0.
func NewImage(img draw.Image) *Canvas {
	w := float64(img.Bounds().Max.X - img.Bounds().Min.X)
	h := float64(img.Bounds().Max.Y - img.Bounds().Min.Y)
	draw.Draw(img, img.Bounds(), image.White, image.ZP, draw.Src)
	gc := draw2d.NewGraphicContext(img)
	gc.SetDPI(dpi)
	gc.Scale(1, -1)
	gc.Translate(0, -h)
	c := &Canvas{
		gc:    gc,
		img:   img,
		w:     vg.Inches(w / dpi),
		h:     vg.Inches(h / dpi),
		color: []color.Color{color.Black},
	}
	vg.Initialize(c)
	return c
}
Ejemplo n.º 3
0
// Save saves the plot to an image file.  Width and height
// are specified in inches, and the file format is determined
// by the extension.  Supported extensions are
// .eps, .jpg, .jpeg, .pdf, .png, .svg, and .tiff.
func (p *Plot) Save(width, height float64, file string) (err error) {
	w, h := vg.Inches(width), vg.Inches(height)
	var c interface {
		vg.Canvas
		Size() (w, h vg.Length)
		io.WriterTo
	}
	switch ext := strings.ToLower(filepath.Ext(file)); ext {

	case ".eps":
		c = vgeps.NewTitle(w, h, file)

	case ".jpg", ".jpeg":
		c = vgimg.JpegCanvas{Canvas: vgimg.New(w, h)}

	case ".pdf":
		c = vgpdf.New(w, h)

	case ".png":
		c = vgimg.PngCanvas{Canvas: vgimg.New(w, h)}

	case ".svg":
		c = vgsvg.New(w, h)

	case ".tiff":
		c = vgimg.TiffCanvas{Canvas: vgimg.New(w, h)}

	default:
		return fmt.Errorf("Unsupported file extension: %s", ext)
	}
	p.Draw(MakeDrawArea(c))

	f, err := os.Create(file)
	if err != nil {
		return err
	}
	if _, err = c.WriteTo(f); err != nil {
		return err
	}
	return f.Close()
}