-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathfunctions.go
105 lines (92 loc) · 2.47 KB
/
functions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright ©2019 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hplot
import (
"math"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
)
// Function implements the Plotter interface,
// drawing a line for the given function.
type Function struct {
F func(x float64) (y float64)
// XMin and XMax specify the range
// of x values to pass to F.
XMin, XMax float64
Samples int
draw.LineStyle
// LogY allows rendering with a log-scaled Y axis.
// When enabled, function values returning 0 will be discarded from
// the final plot.
LogY bool
}
// NewFunction returns a Function that plots F using
// the default line style with 50 samples.
func NewFunction(f func(float64) float64) *Function {
return &Function{
F: f,
Samples: 50,
LineStyle: plotter.DefaultLineStyle,
}
}
// Plot implements the Plotter interface, drawing a line
// that connects each point in the Line.
func (f *Function) Plot(c draw.Canvas, p *plot.Plot) {
trX, trY := p.Transforms(&c)
min, max := f.XMin, f.XMax
if min == 0 && max == 0 {
min = p.X.Min
max = p.X.Max
}
d := (max - min) / float64(f.Samples-1)
switch {
case f.LogY:
var (
line = 0
lines = [][]vg.Point{make([]vg.Point, 0, f.Samples)}
)
for i := range f.Samples {
x := min + float64(i)*d
y := f.F(x)
switch {
case math.IsInf(y, -1) || y <= 0:
line++
lines = append(lines, make([]vg.Point, 0, f.Samples-i))
default:
lines[line] = append(lines[line], vg.Point{
X: trX(x),
Y: trY(y),
})
}
}
for _, line := range lines {
if len(line) <= 1 {
// FIXME(sbinet): we should find a couple of points around...
continue
}
c.StrokeLines(f.LineStyle, c.ClipLinesXY(line)...)
}
default:
line := make([]vg.Point, f.Samples)
for i := range line {
x := min + float64(i)*d
y := f.F(x)
line[i].X = trX(x)
line[i].Y = trY(y)
}
c.StrokeLines(f.LineStyle, c.ClipLinesXY(line)...)
}
}
// Thumbnail draws a line in the given style down the
// center of a DrawArea as a thumbnail representation
// of the LineStyle of the function.
func (f Function) Thumbnail(c *draw.Canvas) {
y := c.Center().Y
c.StrokeLine2(f.LineStyle, c.Min.X, y, c.Max.X, y)
}