Skip to content

Commit

Permalink
Example: Render static images using Orca (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
MetalBlueberry authored Jun 20, 2021
1 parent 144da23 commit ba2cc67
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/static_image/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Static Image

To save Plotly images as static images, you should use the [orca](https://github.com/plotly/orca) project. This example uses a docker image with orca to render a plot to PNG. You can refer to orca documentation to extend this further.
87 changes: 87 additions & 0 deletions examples/static_image/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package main

import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"

grob "github.com/MetalBlueberry/go-plotly/graph_objects"
)

func main() {
/*
fig = dict({
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}
})
*/
fig := &grob.Fig{
Data: grob.Traces{
&grob.Bar{
Type: grob.TraceTypeBar,
X: []float64{1, 2, 3},
Y: []float64{1, 2, 3},
},
},
Layout: &grob.Layout{
Title: &grob.LayoutTitle{
Text: "A Figure Specified By Go Struct",
},
},
}

fmt.Fprint(os.Stderr, "saving to PNG...\n")
err := savePNG(fig, "out.png")
if err != nil {
panic(err)
}
fmt.Fprint(os.Stderr, "Done!\n")
}

func savePNG(fig *grob.Fig, path string) error {
args := "run --rm -i quay.io/plotly/orca graph --format png"
cmd := exec.Command("docker", strings.Split(args, " ")...)

in, err := cmd.StdinPipe()
if err != nil {
return fmt.Errorf("Failed to open StdIn, %w", err)
}
go func() {
err := json.NewEncoder(in).Encode(fig)
if err != nil {
panic(err)
}
err = in.Close()
}()

out, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("Failed to open StdOut, %w", err)
}

f, err := os.Create(path)
if err != nil {
return fmt.Errorf("Cannot create output file")
}
go func() {
defer f.Close()
_, err = io.Copy(f, out)
if err != nil {
panic(err)
}
}()

cmd.Stderr = os.Stderr

err = cmd.Run()
if err != nil {
return fmt.Errorf("Failed to run command, %w", err)
}

return nil
}
Binary file added examples/static_image/out.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit ba2cc67

Please sign in to comment.