...

Source file src/gonum.org/v1/plot/plotter/histogram_example_test.go

Documentation: gonum.org/v1/plot/plotter

     1  // Copyright ©2015 The Gonum 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 plotter_test
     6  
     7  import (
     8  	"image/color"
     9  	"log"
    10  	"math"
    11  
    12  	"golang.org/x/exp/rand"
    13  
    14  	"gonum.org/v1/plot"
    15  	"gonum.org/v1/plot/plotter"
    16  	"gonum.org/v1/plot/vg"
    17  )
    18  
    19  // An example of making a histogram.
    20  func ExampleHistogram() {
    21  	rnd := rand.New(rand.NewSource(1))
    22  
    23  	// stdNorm returns the probability of drawing a
    24  	// value from a standard normal distribution.
    25  	stdNorm := func(x float64) float64 {
    26  		const sigma = 1.0
    27  		const mu = 0.0
    28  		const root2π = 2.50662827459517818309
    29  		return 1.0 / (sigma * root2π) * math.Exp(-((x-mu)*(x-mu))/(2*sigma*sigma))
    30  	}
    31  
    32  	n := 10000
    33  	vals := make(plotter.Values, n)
    34  	for i := 0; i < n; i++ {
    35  		vals[i] = rnd.NormFloat64()
    36  	}
    37  
    38  	p := plot.New()
    39  	p.Title.Text = "Histogram"
    40  	h, err := plotter.NewHist(vals, 16)
    41  	if err != nil {
    42  		log.Panic(err)
    43  	}
    44  	h.Normalize(1)
    45  	p.Add(h)
    46  
    47  	// The normal distribution function
    48  	norm := plotter.NewFunction(stdNorm)
    49  	norm.Color = color.RGBA{R: 255, A: 255}
    50  	norm.Width = vg.Points(2)
    51  	p.Add(norm)
    52  
    53  	err = p.Save(200, 200, "testdata/histogram.png")
    54  	if err != nil {
    55  		log.Panic(err)
    56  	}
    57  }
    58  
    59  func ExampleHistogram_logScaleY() {
    60  	p := plot.New()
    61  	p.Title.Text = "Histogram in log-y"
    62  	p.Y.Scale = plot.LogScale{}
    63  	p.Y.Tick.Marker = plot.LogTicks{Prec: -1}
    64  	p.Y.Label.Text = "Y"
    65  	p.X.Label.Text = "X"
    66  
    67  	h1, err := plotter.NewHist(plotter.Values{
    68  		-2, -2,
    69  		-1,
    70  		+3, +3, +3, +3,
    71  		+1, +1, +1, +1, +1, +1, +1, +1, +1, +1,
    72  		+1, +1, +1, +1, +1, +1, +1, +1, +1, +1,
    73  	}, 16)
    74  	if err != nil {
    75  		log.Fatal(err)
    76  	}
    77  	h1.LogY = true
    78  	h1.FillColor = color.RGBA{255, 0, 0, 255}
    79  
    80  	h2, err := plotter.NewHist(plotter.Values{
    81  		-3, -3, -3,
    82  		+2, +2, +2, +2, +2,
    83  	}, 16)
    84  
    85  	if err != nil {
    86  		log.Fatal(err)
    87  	}
    88  
    89  	h2.LogY = true
    90  	h2.FillColor = color.RGBA{0, 0, 255, 255}
    91  
    92  	p.Add(h1, h2, plotter.NewGrid())
    93  
    94  	err = p.Save(200, 200, "testdata/histogram_logy.png")
    95  	if err != nil {
    96  		log.Fatal(err)
    97  	}
    98  }
    99  

View as plain text