|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "strings" |
| 10 | + |
| 11 | + grob "github.com/MetalBlueberry/go-plotly/graph_objects" |
| 12 | +) |
| 13 | + |
| 14 | +func main() { |
| 15 | + /* |
| 16 | + fig = dict({ |
| 17 | + "data": [{"type": "bar", |
| 18 | + "x": [1, 2, 3], |
| 19 | + "y": [1, 3, 2]}], |
| 20 | + "layout": {"title": {"text": "A Figure Specified By Python Dictionary"}} |
| 21 | + }) |
| 22 | + */ |
| 23 | + fig := &grob.Fig{ |
| 24 | + Data: grob.Traces{ |
| 25 | + &grob.Bar{ |
| 26 | + Type: grob.TraceTypeBar, |
| 27 | + X: []float64{1, 2, 3}, |
| 28 | + Y: []float64{1, 2, 3}, |
| 29 | + }, |
| 30 | + }, |
| 31 | + Layout: &grob.Layout{ |
| 32 | + Title: &grob.LayoutTitle{ |
| 33 | + Text: "A Figure Specified By Go Struct", |
| 34 | + }, |
| 35 | + }, |
| 36 | + } |
| 37 | + |
| 38 | + fmt.Fprint(os.Stderr, "saving to PNG...\n") |
| 39 | + err := savePNG(fig, "out.png") |
| 40 | + if err != nil { |
| 41 | + panic(err) |
| 42 | + } |
| 43 | + fmt.Fprint(os.Stderr, "Done!\n") |
| 44 | +} |
| 45 | + |
| 46 | +func savePNG(fig *grob.Fig, path string) error { |
| 47 | + args := "run --rm -i quay.io/plotly/orca graph --format png" |
| 48 | + cmd := exec.Command("docker", strings.Split(args, " ")...) |
| 49 | + |
| 50 | + in, err := cmd.StdinPipe() |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("Failed to open StdIn, %w", err) |
| 53 | + } |
| 54 | + go func() { |
| 55 | + err := json.NewEncoder(in).Encode(fig) |
| 56 | + if err != nil { |
| 57 | + panic(err) |
| 58 | + } |
| 59 | + err = in.Close() |
| 60 | + }() |
| 61 | + |
| 62 | + out, err := cmd.StdoutPipe() |
| 63 | + if err != nil { |
| 64 | + return fmt.Errorf("Failed to open StdOut, %w", err) |
| 65 | + } |
| 66 | + |
| 67 | + f, err := os.Create(path) |
| 68 | + if err != nil { |
| 69 | + return fmt.Errorf("Cannot create output file") |
| 70 | + } |
| 71 | + go func() { |
| 72 | + defer f.Close() |
| 73 | + _, err = io.Copy(f, out) |
| 74 | + if err != nil { |
| 75 | + panic(err) |
| 76 | + } |
| 77 | + }() |
| 78 | + |
| 79 | + cmd.Stderr = os.Stderr |
| 80 | + |
| 81 | + err = cmd.Run() |
| 82 | + if err != nil { |
| 83 | + return fmt.Errorf("Failed to run command, %w", err) |
| 84 | + } |
| 85 | + |
| 86 | + return nil |
| 87 | +} |
0 commit comments