...

Source file src/gonum.org/v1/plot/plotter/functions.go

Documentation: gonum.org/v1/plot/plotter

     1  // Copyright ©2015 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package plotter
     6  
     7  import (
     8  	"gonum.org/v1/plot"
     9  	"gonum.org/v1/plot/vg"
    10  	"gonum.org/v1/plot/vg/draw"
    11  )
    12  
    13  // Function implements the Plotter interface,
    14  // drawing a line for the given function.
    15  type Function struct {
    16  	F func(x float64) (y float64)
    17  
    18  	// XMin and XMax specify the range
    19  	// of x values to pass to F.
    20  	XMin, XMax float64
    21  
    22  	Samples int
    23  
    24  	draw.LineStyle
    25  }
    26  
    27  // NewFunction returns a Function that plots F using
    28  // the default line style with 50 samples.
    29  func NewFunction(f func(float64) float64) *Function {
    30  	return &Function{
    31  		F:         f,
    32  		Samples:   50,
    33  		LineStyle: DefaultLineStyle,
    34  	}
    35  }
    36  
    37  // Plot implements the Plotter interface, drawing a line
    38  // that connects each point in the Line.
    39  func (f *Function) Plot(c draw.Canvas, p *plot.Plot) {
    40  	trX, trY := p.Transforms(&c)
    41  
    42  	min, max := f.XMin, f.XMax
    43  	if min == 0 && max == 0 {
    44  		min = p.X.Min
    45  		max = p.X.Max
    46  	}
    47  	d := (max - min) / float64(f.Samples-1)
    48  	line := make([]vg.Point, f.Samples)
    49  	for i := range line {
    50  		x := min + float64(i)*d
    51  		line[i].X = trX(x)
    52  		line[i].Y = trY(f.F(x))
    53  	}
    54  	c.StrokeLines(f.LineStyle, c.ClipLinesXY(line)...)
    55  }
    56  
    57  // Thumbnail draws a line in the given style down the
    58  // center of a DrawArea as a thumbnail representation
    59  // of the LineStyle of the function.
    60  func (f Function) Thumbnail(c *draw.Canvas) {
    61  	y := c.Center().Y
    62  	c.StrokeLine2(f.LineStyle, c.Min.X, y, c.Max.X, y)
    63  }
    64  

View as plain text