go-hep.org/x/hep@v0.38.1/hplot/plot.go (about) 1 // Copyright ©2020 The go-hep Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package hplot 6 7 import ( 8 "io" 9 "math" 10 "sync" 11 12 "gonum.org/v1/plot" 13 "gonum.org/v1/plot/vg" 14 "gonum.org/v1/plot/vg/draw" 15 ) 16 17 // Plot is the basic type representing a plot. 18 type Plot struct { 19 *plot.Plot 20 Style Style 21 } 22 23 // muNewPlot protects access to gonum/plot.DefaultFont 24 var muNewPlot sync.Mutex 25 26 // New returns a new plot with some reasonable 27 // default settings. 28 func New() *Plot { 29 muNewPlot.Lock() 30 defer muNewPlot.Unlock() 31 32 style := DefaultStyle 33 defer style.reset(plot.DefaultFont) 34 plot.DefaultFont = style.Fonts.Default 35 36 pp := &Plot{ 37 Plot: plot.New(), 38 Style: style, 39 } 40 pp.Style.Apply(pp) 41 return pp 42 } 43 44 // Add adds a Plotters to the plot. 45 // 46 // If the plotters implements DataRanger then the 47 // minimum and maximum values of the X and Y 48 // axes are changed if necessary to fit the range of 49 // the data. 50 // 51 // When drawing the plot, Plotters are drawn in the 52 // order in which they were added to the plot. 53 func (p *Plot) Add(ps ...plot.Plotter) { 54 for _, d := range ps { 55 if x, ok := d.(plot.DataRanger); ok { 56 xmin, xmax, ymin, ymax := x.DataRange() 57 p.Plot.X.Min = math.Min(p.Plot.X.Min, xmin) 58 p.Plot.X.Max = math.Max(p.Plot.X.Max, xmax) 59 p.Plot.Y.Min = math.Min(p.Plot.Y.Min, ymin) 60 p.Plot.Y.Max = math.Max(p.Plot.Y.Max, ymax) 61 } 62 } 63 64 p.Plot.Add(ps...) 65 } 66 67 // Save saves the plot to an image file. The file format is determined 68 // by the extension. 69 // 70 // Supported extensions are: 71 // 72 // .eps, .jpg, .jpeg, .json, .pdf, .png, .svg, .tex, .tif and .tiff. 73 // 74 // If w or h are <= 0, the value is chosen such that it follows the Golden Ratio. 75 // If w and h are <= 0, the values are chosen such that they follow the Golden Ratio 76 // (the width is defaulted to vgimg.DefaultWidth). 77 func (p *Plot) Save(w, h vg.Length, file string) error { 78 return Save(p, w, h, file) 79 } 80 81 // WriterTo returns an io.WriterTo that will write the plot as 82 // the specified image format. 83 // 84 // Supported formats are: 85 // 86 // eps, jpg|jpeg, pdf, png, svg, tex and tif|tiff. 87 func (p *Plot) WriterTo(w, h vg.Length, format string) (io.WriterTo, error) { 88 return WriterTo(p, w, h, format) 89 } 90 91 // Draw draws a plot to a draw.Canvas. 92 // 93 // Plotters are drawn in the order in which they were 94 // added to the plot. Plotters that implement the 95 // GlyphBoxer interface will have their GlyphBoxes 96 // taken into account when padding the plot so that 97 // none of their glyphs are clipped. 98 func (p *Plot) Draw(dc draw.Canvas) { 99 p.Plot.Draw(dc) 100 } 101 102 var ( 103 _ Drawer = (*Plot)(nil) 104 )