Created
May 26, 2018 18:12
-
-
Save jakelacey2012/9c34966fe3518ad4bc7529cb20eed38c to your computer and use it in GitHub Desktop.
ml-go-jff-eps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
// for _, xy := range xys { | |
// fmt.Println(xy.x, xy.y) | |
// } | |
p, err := plot.New() | |
if err != nil { | |
log.Fatalf("could not create plot: %v", err) | |
} | |
pxys := make(plotter.XYs, len(xys)) | |
for i, xy := range xys { | |
pxys[i].X = xy.x | |
pxys[i].Y = xy.y | |
} | |
scatter, err := plotter.NewScatter(pxys) | |
if err != nil { | |
log.Fatalf("could not create scatter: %v", err) | |
} | |
scatter.GlyphStyle.Shape = draw.CrossGlyph{} | |
scatter.Color = color.RGBA{R: 255, A: 255} | |
p.Add(scatter) | |
wt, err := p.WriterTo(512, 512, "png") | |
if err != nil { | |
log.Fatalf("could not create writer: %v", err) | |
} | |
imageFile, err := os.Create("out.png") | |
if err != nil { | |
log.Fatalf("could not create image file: %v", err) | |
} | |
_, err = wt.WriteTo(imageFile) | |
if err != nil { | |
log.Fatalf("could not write to out.png: %v", err) | |
} | |
if err := imageFile.Close(); err != nil { | |
log.Fatalf("could not close out.png: %v", err) | |
} | |
} | |
type xy struct { | |
x, y float64 | |
} | |
func readData(path string) ([]xy, error) { | |
file, err := os.Open(path) | |
if err != nil { | |
return nil, err | |
} | |
defer file.Close() | |
var xys []xy | |
scanner := bufio.NewScanner(file) | |
for scanner.Scan() { | |
var x, y float64 | |
_, err := fmt.Sscanf(scanner.Text(), "%f,%f", &x, &y) | |
if err != nil { | |
log.Printf("discarding bad data point %q: %v", scanner.Text(), err) | |
} | |
xys = append(xys, xy{x, y}) | |
} | |
if err := scanner.Err(); err != nil { | |
return nil, fmt.Errorf("could not scan: %v", err) | |
} | |
return xys, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment