go-hep.org/x/hep@v0.38.1/hplot/h2d_example_test.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_test
     6  
     7  import (
     8  	"log"
     9  	"math/rand/v2"
    10  
    11  	"go-hep.org/x/hep/hbook"
    12  	"go-hep.org/x/hep/hplot"
    13  	"gonum.org/v1/gonum/mat"
    14  	"gonum.org/v1/gonum/stat/distmv"
    15  	"gonum.org/v1/plot/plotter"
    16  	"gonum.org/v1/plot/vg"
    17  )
    18  
    19  func ExampleH2D() {
    20  	h := hbook.NewH2D(100, -10, 10, 100, -10, 10)
    21  
    22  	const npoints = 10000
    23  
    24  	dist, ok := distmv.NewNormal(
    25  		[]float64{0, 1},
    26  		mat.NewSymDense(2, []float64{4, 0, 0, 2}),
    27  		rand.New(rand.NewPCG(1234, 1234)),
    28  	)
    29  	if !ok {
    30  		log.Fatalf("error creating distmv.Normal")
    31  	}
    32  
    33  	v := make([]float64, 2)
    34  	// Draw some random values from the standard
    35  	// normal distribution.
    36  	for range npoints {
    37  		v = dist.Rand(v)
    38  		h.Fill(v[0], v[1], 1)
    39  	}
    40  
    41  	p := hplot.New()
    42  	p.Title.Text = "Hist-2D"
    43  	p.X.Label.Text = "x"
    44  	p.Y.Label.Text = "y"
    45  
    46  	p.Add(hplot.NewH2D(h, nil))
    47  	p.Add(plotter.NewGrid())
    48  	err := p.Save(10*vg.Centimeter, 10*vg.Centimeter, "testdata/h2d_plot.png")
    49  	if err != nil {
    50  		log.Fatal(err)
    51  	}
    52  }
    53  
    54  func ExampleH2D_withLegend() {
    55  	h2d := hbook.NewH2D(100, -10, 10, 100, -10, 10)
    56  
    57  	const npoints = 10000
    58  
    59  	dist, ok := distmv.NewNormal(
    60  		[]float64{0, 1},
    61  		mat.NewSymDense(2, []float64{4, 0, 0, 2}),
    62  		rand.New(rand.NewPCG(1234, 1234)),
    63  	)
    64  	if !ok {
    65  		log.Fatalf("error creating distmv.Normal")
    66  	}
    67  
    68  	v := make([]float64, 2)
    69  	// Draw some random values from the standard
    70  	// normal distribution.
    71  	for range npoints {
    72  		v = dist.Rand(v)
    73  		h2d.Fill(v[0], v[1], 1)
    74  	}
    75  	h := hplot.NewH2D(h2d, nil)
    76  
    77  	p := hplot.New()
    78  	p.Title.Text = "Hist-2D"
    79  	p.X.Label.Text = "x"
    80  	p.Y.Label.Text = "y"
    81  
    82  	p.Add(h)
    83  	p.Add(plotter.NewGrid())
    84  
    85  	fig := hplot.Figure(p, hplot.WithLegend(h.Legend()))
    86  	err := hplot.Save(fig, 10*vg.Centimeter, 10*vg.Centimeter, "testdata/h2d_plot_legend.png")
    87  	if err != nil {
    88  		log.Fatal(err)
    89  	}
    90  }