go-hep.org/x/hep@v0.38.1/hplot/h2d.go (about)

     1  // Copyright ©2016 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  	"fmt"
     9  
    10  	"go-hep.org/x/hep/hbook"
    11  	"gonum.org/v1/plot"
    12  	"gonum.org/v1/plot/palette"
    13  	"gonum.org/v1/plot/palette/brewer"
    14  	"gonum.org/v1/plot/plotter"
    15  	"gonum.org/v1/plot/vg/draw"
    16  )
    17  
    18  // H2D implements the plotter.Plotter interface,
    19  // drawing a 2-dim histogram of the data.
    20  type H2D struct {
    21  	// H is the histogramming data
    22  	H *hbook.H2D
    23  
    24  	// InfoStyle is the style of infos displayed for
    25  	// the histogram (entries, mean, rms)
    26  	Infos HInfos
    27  
    28  	// HeatMap implements the Plotter interface, drawing
    29  	// a heat map of the values in the 2-d histogram.
    30  	HeatMap *plotter.HeatMap
    31  }
    32  
    33  // NewH2D returns a new 2-dim histogram from a hbook.H2D.
    34  func NewH2D(h *hbook.H2D, p palette.Palette) *H2D {
    35  	if p == nil {
    36  		p, _ = brewer.GetPalette(brewer.TypeAny, "RdYlBu", 11)
    37  	}
    38  	return &H2D{
    39  		H:       h,
    40  		HeatMap: plotter.NewHeatMap(h.GridXYZ(), p),
    41  	}
    42  }
    43  
    44  // Plot implements the Plotter interface, drawing a line
    45  // that connects each point in the Line.
    46  func (h *H2D) Plot(c draw.Canvas, p *plot.Plot) {
    47  	h.HeatMap.Plot(c, p)
    48  }
    49  
    50  // DataRange implements the DataRange method
    51  // of the plot.DataRanger interface.
    52  func (h *H2D) DataRange() (xmin, xmax, ymin, ymax float64) {
    53  	return h.HeatMap.DataRange()
    54  }
    55  
    56  // GlyphBoxes returns a slice of GlyphBoxes,
    57  // one for each of the bins, implementing the
    58  // plot.GlyphBoxer interface.
    59  func (h *H2D) GlyphBoxes(p *plot.Plot) []plot.GlyphBox {
    60  	return h.HeatMap.GlyphBoxes(p)
    61  }
    62  
    63  // Legend returns a legend constructed from the 2-dim data and palette.
    64  func (h *H2D) Legend() Legend {
    65  	legend := NewLegend()
    66  	thumbs := plotter.PaletteThumbnailers(h.HeatMap.Palette)
    67  	for i := len(thumbs) - 1; i >= 0; i-- {
    68  		t := thumbs[i]
    69  		if i != 0 && i != len(thumbs)-1 {
    70  			legend.Add("", t)
    71  			continue
    72  		}
    73  		var val float64
    74  		switch i {
    75  		case 0:
    76  			val = h.HeatMap.Min
    77  		case len(thumbs) - 1:
    78  			val = h.HeatMap.Max
    79  		}
    80  		legend.Add(fmt.Sprintf("%.2g", val), t)
    81  	}
    82  	legend.Top = true
    83  
    84  	return legend
    85  }
    86  
    87  // check interfaces
    88  var _ plot.Plotter = (*H2D)(nil)
    89  var _ plot.DataRanger = (*H2D)(nil)
    90  var _ plot.GlyphBoxer = (*H2D)(nil)