-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplot.go
More file actions
451 lines (382 loc) · 9.9 KB
/
Copy pathplot.go
File metadata and controls
451 lines (382 loc) · 9.9 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package tfutil
import (
"errors"
"fmt"
"image"
"image/color"
"math"
"gonum.org/v1/gonum/floats"
"os"
"gonum.org/v1/gonum/mat"
"gonum.org/v1/gonum/stat/distuv"
"gonum.org/v1/plot"
"gonum.org/v1/plot/palette/moreland"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"gonum.org/v1/plot/vg/vgimg"
)
//ScatterData store scatter data
type ScatterData struct {
//using key to contact the xys and colors, and key will be
// the name of the scatter data
XYZsList map[string]plotter.XYZs
}
//Add add new item to scatter data list, the new item marked by name
func (s *ScatterData) Add(name string, xs, ys, zs []float64) error {
if len(xs) != len(ys) || len(xs) != len(zs) {
return (errors.New("wrong length"))
}
// init xyzs data
xyzs := make(plotter.XYZs, len(xs))
for i := 0; i < len(xs); i++ {
xyzs[i].X, xyzs[i].Y, xyzs[i].Z = xs[i], ys[i], zs[i]
}
if s.XYZsList == nil {
s.XYZsList = make(map[string]plotter.XYZs)
}
if _, ok := s.XYZsList[name]; ok {
delete(s.XYZsList, name)
}
s.XYZsList[name] = xyzs
return nil
}
//Del delete item marked by name from the catter data list
func (s *ScatterData) Del(name string) {
if s.XYZsList == nil {
return
}
if _, ok := s.XYZsList[name]; ok {
delete(s.XYZsList, name)
}
return
}
//Clear clear scatter data list
func (s *ScatterData) Clear() {
for k := range s.XYZsList {
delete(s.XYZsList, k)
}
return
}
//SaveLine save line ,the line's X is index of slice, the Y is item's value
//for example , <i, line[i]> is a pixel in the line
func SaveLine(outfileName string, line []float64) {
if len(line) < 1 {
return
}
costData := make(plotter.XYZs, len(line))
for i := range costData {
costData[i].X = float64(i)
costData[i].Y = line[i]
}
// Create a new plot, set its title and
// axis labels.
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = outfileName
p.X.Label.Text = "X"
p.Y.Label.Text = "Y"
// Draw a grid behind the data
p.Add(plotter.NewGrid())
// Make a line plotter and set its style.
l, err := plotter.NewLine(costData)
if err != nil {
panic(err)
}
l.LineStyle.Width = vg.Points(1)
//l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
l.LineStyle.Color = color.RGBA{B: 255, A: 255}
p.Add(l)
// Add the plotters to the plot, with a legend
// entry for each
//p.Legend.Add("hypothesis", l)
// Save the plot to a PNG file.
if err := p.Save(4*vg.Inch, 4*vg.Inch, outfileName+".png"); err != nil {
panic(err)
}
}
//SaveResidualPlot save residual plots to png file named outfileName
func SaveResidualPlot(outfileName string, X *mat.Dense, y, theta mat.Vector) {
var h, diff mat.VecDense
h.MulVec(X, theta)
diff.SubVec(y, &h)
l := y.Len()
hyXYs, yXYs, diffXYs := make(plotter.XYZs, l), make(plotter.XYZs, l), make(plotter.XYZs, l)
for i := 0; i < l; i++ {
hyXYs[i].X = float64(i)
hyXYs[i].Y = h.AtVec(i)
yXYs[i].X = float64(i)
yXYs[i].Y = y.AtVec(i)
diffXYs[i].X = float64(i)
diffXYs[i].Y = diff.AtVec(i)
}
// Create a new plot, set its title and
// axis labels.
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = outfileName
p.X.Label.Text = "X"
p.Y.Label.Text = "Y"
// Draw a grid behind the data
p.Add(plotter.NewGrid())
// draw cost line
// Make a line plotter and set its style.
hyL, err := plotter.NewLine(hyXYs)
if err != nil {
panic(err)
}
hyL.LineStyle.Width = vg.Points(1)
//l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
hyL.LineStyle.Color = color.RGBA{B: 255, A: 255}
yL, err := plotter.NewLine(yXYs)
if err != nil {
panic(err)
}
yL.LineStyle.Width = vg.Points(1)
//l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
yL.LineStyle.Color = color.RGBA{R: 255, B: 128, A: 255}
diffL, err := plotter.NewLine(diffXYs)
if err != nil {
panic(err)
}
diffL.LineStyle.Width = vg.Points(1)
diffL.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
diffL.LineStyle.Color = color.RGBA{R: 128, B: 128, A: 128}
p.Add(hyL, yL, diffL)
// Add the plotters to the plot, with a legend
// entry for each
p.Legend.Add("hyL", hyL)
p.Legend.Add("yL", yL)
// Save the plot to a PNG file.
if err := p.Save(4*vg.Inch, 4*vg.Inch, outfileName+".png"); err != nil {
panic(err)
}
}
// SaveScatters show multi scatters
// if samePlot is true, all of scatters will be show in one plot,otherwise will be
// show in separate plot
func SaveScatters(outfileName string, scatters ...*ScatterData) {
rows, cols := func() (int, int) {
t := (len(scatters) / 2)
if t == 0 {
return 1, 1
} else if len(scatters) > t*2 {
return t + 1, 2
}
return t, 2
}()
plots := make([][]*plot.Plot, rows)
for j := 0; j < rows; j++ {
plots[j] = make([]*plot.Plot, cols)
}
for i, xyzs := range scatters {
p, err := plot.New()
if err != nil {
panic(err)
}
for name, sdata := range xyzs.XYZsList {
// Make a scatter plotter and set its style.
s, err := myNewScatter(sdata)
if err != nil {
panic(err)
}
p.Add(s)
p.Legend.Add(fmt.Sprint("", name), s)
}
//i:=k*row + col
row, col := i/2, i%2
plots[row][col] = p
}
img := vgimg.New(vg.Points(750), vg.Points(475))
dc := draw.New(img)
t := draw.Tiles{
Rows: rows,
Cols: cols,
}
canvases := plot.Align(plots, t, dc)
for j := 0; j < rows; j++ {
for i := 0; i < cols; i++ {
if plots[j][i] != nil {
plots[j][i].Draw(canvases[j][i])
}
}
}
w, err := os.Create(outfileName + ".png")
if err != nil {
panic(err)
}
png := vgimg.PngCanvas{Canvas: img}
if _, err := png.WriteTo(w); err != nil {
panic(err)
}
}
func myNewScatter(sdata plotter.XYZs) (s *plotter.Scatter, err error) {
// Make a scatter plotter and set its style.
s, err = plotter.NewScatter(sdata)
if err != nil {
return
}
// Calculate the range of Z values.
minZ, maxZ := math.Inf(1), math.Inf(-1)
for _, xyz := range sdata {
if xyz.Z > maxZ {
maxZ = xyz.Z
}
if xyz.Z < minZ {
minZ = xyz.Z
}
}
//protoc when maxZ == minZ
maxZ = maxZ + 1
//
colors := moreland.Kindlmann() // Initialize a color map.
colors.SetMax(1 + maxZ)
colors.SetMin(minZ)
// Specify style and color for individual points.
s.GlyphStyleFunc = func(i int) draw.GlyphStyle {
_, _, z := sdata.XYZ(i)
d := (z - minZ) / (maxZ - minZ)
rng := maxZ - minZ
k := d*rng + minZ
c, err := colors.At(k)
if err != nil {
panic(err)
}
return draw.GlyphStyle{Color: c, Radius: vg.Points(3), Shape: draw.CircleGlyph{}}
}
return
}
// func myNewLegend(p *plot.Plot, minZ,maxZ float64) {
// //////////
// //Create a legend
// thumbs := plotter.PaletteThumbnailers(colors.Palette(n))
// for i := len(thumbs) - 1; i >= 0; i-- {
// t := thumbs[i]
// if i != 0 && i != len(thumbs)-1 {
// p.Legend.Add("", t)
// continue
// }
// var val int
// switch i {
// case 0:
// val = int(minZ)
// case len(thumbs) - 1:
// val = int(maxZ)
// }
// p.Legend.Add(fmt.Sprintf("%d", val), t)
// }
// // This is the width of the legend, experimentally determined.
// const legendWidth = vg.Centimeter
// // Slide the legend over so it doesn't overlap the ScatterPlot.
// p.Legend.XOffs = legendWidth
// //////////
// }
//SaveScatterToImage deal the data as a image matrix,
//it will draw all of item in the data as a pixel
//each item in the data will be dealed as the Gray intensity
func SaveScatterToImage(outfileName string, r, c int, data []float64) (err error) {
p, err := plot.New()
if err != nil {
panic(err)
}
//p.Title.Text = "A Logo"
img, err := newGray(r, c, data)
if err != nil {
return
}
p.Add(img)
err = p.Save(5*vg.Centimeter, 5*vg.Centimeter, outfileName+".png")
return
}
// newGray create a plotter image from scatter data
func newGray(r, c int, data []float64) (img *plotter.Image, err error) {
if r*c != len(data) {
err = errors.New("wrong scatter size")
return
}
pic := image.NewGray(image.Rect(0, 0, r, c))
// assign backgroud to white
for x := 0; x < r; x++ {
for y := 0; y < c; y++ {
pic.SetGray(x, y, color.Gray{255})
}
}
min, max := floats.Min(data), floats.Max(data)
grayScope := max - min
for x := 0; x < r; x++ {
for y := 0; y < c; y++ {
// scaling data to 0~255
d := 255 - math.Round(255*(data[x*c+y]-min)/grayScope)
pic.SetGray(x, y, color.Gray{uint8(d)})
}
}
img = plotter.NewImage(pic, 0, 0, float64(r), float64(c))
return
}
func SaveBoxPlot(outfileName string, datas ...[]float64) {
// Create the plot and set its title and axis label.
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = "Box plots"
p.Y.Label.Text = "Values"
// Make boxes for our data and add them to the plot.
locName := make([]string, 0)
w := vg.Points(40)
for loc, data := range datas {
values := make(plotter.Values, len(data))
for j := 0; j < len(data); j++ {
values[j] = data[j]
}
locName = append(locName, fmt.Sprintf("%v", loc))
b, err := plotter.NewBoxPlot(w, float64(loc), values)
if err != nil {
panic(err)
}
p.Add(b)
}
// Set the X axis of the plot to nominal with
// the given names for x=0, x=1 and x=2.
p.NominalX(locName...)
if err := p.Save(3*vg.Inch, 4*vg.Inch, outfileName+".png"); err != nil {
panic(err)
}
}
func SaveHistograms(outfileName string, data []float64) {
// Draw some random values from the standard
// normal distribution.
v := make(plotter.Values, len(data))
for i := 0; i < len(data); i++ {
v[i] = data[i]
}
// Make a plot and set its title.
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = "Histogram"
// Create a histogram of our values drawn
// from the standard normal.
h, err := plotter.NewHist(v, 16)
if err != nil {
panic(err)
}
// Normalize the area under the histogram to
// sum to one.
h.Normalize(1)
p.Add(h)
// The normal distribution function
norm := plotter.NewFunction(distuv.UnitNormal.Prob)
norm.Color = color.RGBA{R: 255, A: 255}
norm.Width = vg.Points(2)
p.Add(norm)
// Save the plot to a PNG file.
if err := p.Save(4*vg.Inch, 4*vg.Inch, "hist-"+outfileName+".png"); err != nil {
panic(err)
}
}