-
Notifications
You must be signed in to change notification settings - Fork 195
/
main.go
100 lines (86 loc) · 1.95 KB
/
main.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
package main
import (
"bufio"
"fmt"
"image/color"
"log"
"os"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg/draw"
)
func main() {
xys, err := readData("data.txt")
if err != nil {
log.Fatalf("could not read data.txt: %v", err)
}
_ = xys
err = plotData("out.png", xys)
if err != nil {
log.Fatalf("could not plot data: %v", err)
}
}
type xy struct{ x, y float64 }
func readData(path string) (plotter.XYs, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var xys plotter.XYs
s := bufio.NewScanner(f)
for s.Scan() {
var x, y float64
_, err := fmt.Sscanf(s.Text(), "%f,%f", &x, &y)
if err != nil {
log.Printf("discarding bad data point %q: %v", s.Text(), err)
continue
}
xys = append(xys, struct{ X, Y float64 }{x, y})
}
if err := s.Err(); err != nil {
return nil, fmt.Errorf("could not scan: %v", err)
}
return xys, nil
}
func plotData(path string, xys plotter.XYs) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("could not create %s: %v", path, err)
}
p, err := plot.New()
if err != nil {
return fmt.Errorf("could not create plot: %v", err)
}
// create scatter with all data points
s, err := plotter.NewScatter(xys)
if err != nil {
return fmt.Errorf("could not create scatter: %v", err)
}
s.GlyphStyle.Shape = draw.CrossGlyph{}
s.Color = color.RGBA{R: 255, A: 255}
p.Add(s)
var x, c float64
x = 1.2
c = -3
// create fake linear regression result
l, err := plotter.NewLine(plotter.XYs{
{3, 3*x + c}, {20, 20*x + c},
})
if err != nil {
return fmt.Errorf("could not create line: %v", err)
}
p.Add(l)
wt, err := p.WriterTo(256, 256, "png")
if err != nil {
return fmt.Errorf("could not create writer: %v", err)
}
_, err = wt.WriteTo(f)
if err != nil {
return fmt.Errorf("could not write to %s: %v", path, err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("could not close %s: %v", path, err)
}
return nil
}