...

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

Documentation: gonum.org/v1/plot/plotter

     1  // Copyright ©2016 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  	"time"
    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  	"gonum.org/v1/plot/vg/draw"
    18  )
    19  
    20  // Example_timeSeries draws a time series.
    21  func Example_timeSeries() {
    22  	rnd := rand.New(rand.NewSource(1))
    23  
    24  	// xticks defines how we convert and display time.Time values.
    25  	xticks := plot.TimeTicks{Format: "2006-01-02\n15:04"}
    26  
    27  	// randomPoints returns some random x, y points
    28  	// with some interesting kind of trend.
    29  	randomPoints := func(n int) plotter.XYs {
    30  		const (
    31  			month = 1
    32  			day   = 1
    33  			hour  = 1
    34  			min   = 1
    35  			sec   = 1
    36  			nsec  = 1
    37  		)
    38  		pts := make(plotter.XYs, n)
    39  		for i := range pts {
    40  			date := time.Date(2007+i, month, day, hour, min, sec, nsec, time.UTC).Unix()
    41  			pts[i].X = float64(date)
    42  			pts[i].Y = float64(pts[i].X+10*rnd.Float64()) * 1e-9
    43  		}
    44  		return pts
    45  	}
    46  
    47  	n := 10
    48  	data := randomPoints(n)
    49  
    50  	p := plot.New()
    51  	p.Title.Text = "Time Series"
    52  	p.X.Tick.Marker = xticks
    53  	p.Y.Label.Text = "Number of Gophers\n(Billions)"
    54  	p.Add(plotter.NewGrid())
    55  
    56  	line, points, err := plotter.NewLinePoints(data)
    57  	if err != nil {
    58  		log.Panic(err)
    59  	}
    60  	line.Color = color.RGBA{G: 255, A: 255}
    61  	points.Shape = draw.CircleGlyph{}
    62  	points.Color = color.RGBA{R: 255, A: 255}
    63  
    64  	p.Add(line, points)
    65  
    66  	err = p.Save(10*vg.Centimeter, 5*vg.Centimeter, "testdata/timeseries.png")
    67  	if err != nil {
    68  		log.Panic(err)
    69  	}
    70  }
    71  

View as plain text