github.com/tobgu/qframe@v0.4.0/contrib/gonum/qplot/qplot.go (about) 1 package qplot 2 3 import ( 4 "bytes" 5 "io" 6 7 "gonum.org/v1/plot" 8 9 "github.com/tobgu/qframe/qerrors" 10 ) 11 12 // QPlot is a abstraction over Gonum's plotting interface 13 // for a less verbose experience in interactive environments 14 // such as Jypter notebooks. 15 type QPlot struct { 16 Config 17 } 18 19 // NewQPlot returns a new QPlot. 20 func NewQPlot(cfg Config) QPlot { 21 return QPlot{Config: cfg} 22 } 23 24 // WriteTo writes a plot to an io.Writer 25 func (qp QPlot) WriteTo(writer io.Writer) error { 26 plt, err := plot.New() 27 if err != nil { 28 return err 29 } 30 for _, fn := range qp.Plotters { 31 pltr, err := fn(plt) 32 if err != nil { 33 return qerrors.Propagate("WriteTo", err) 34 } 35 plt.Add(pltr) 36 } 37 if qp.PlotConfig != nil { 38 qp.PlotConfig(plt) 39 } 40 w, err := plt.WriterTo(qp.Width, qp.Height, string(qp.Format)) 41 if err != nil { 42 return err 43 } 44 _, err = w.WriteTo(writer) 45 return err 46 } 47 48 // Bytes returns a plot in the configured FormatType. 49 func (qp QPlot) Bytes() ([]byte, error) { 50 buf := bytes.NewBuffer(nil) 51 err := qp.WriteTo(buf) 52 if err != nil { 53 return nil, qerrors.Propagate("Bytes", err) 54 } 55 return buf.Bytes(), nil 56 } 57 58 // MustBytes returns a plot in the configured FormatType 59 // and panics if it encounters an error. 60 func (qp QPlot) MustBytes() []byte { 61 raw, err := qp.Bytes() 62 if err != nil { 63 panic(qerrors.Propagate("MustBytes", err)) 64 } 65 return raw 66 }