Production Level Knowledge & Tips

  1. 未分類
  2. 8 view

[Plotinum][Go]Draw chart with Go lang

Outline

We can draw charts with Go lang using Plotinum.
I’ll draw a chart with the library.

Install

It’s easy. Just type following command.
go get code.google.com/p/plotinum/...

Sample Program

plotinum-target-func
We can check sample source codes here.
I’ll try to draw a chart represents following formula.
w is white Gaussian noise with N(1, 0.05) (average is 1 and variance is 0.05).
package main

import (
  "code.google.com/p/plotinum/plot"
  "code.google.com/p/plotinum/plotter"
  "image/color"
  "math/rand"
  "math"
)

// Generate Gaussian white noise by Box-Mullar Transform
func normalRand(mu, sigma float64) float64 {
  z := math.Sqrt(-2.0 * math.Log(rand.Float64())) * math.Sin(2.0 * math.Pi * rand.Float64())
  return sigma*z + mu
}

// Make sequence of numbers with common difference
func linspace(start, end float64, n int, x plotter.XYs) {
  for i := 0; i < n; i++ {
    t := float64(i) / float64(n-1)
    x[i].X = (1.0 - t) * start + t * end
  }
}

func main() {
  //===================================================
  // Make observed points

  rand.Seed(int64(0))

  // Prepare X axis of observed points
  n := 50
  answer := make(plotter.XYs, n)
  linspace(-3, 3, n, answer)

  // make observed points
  pix := make([]float64, n)
  for i := 0; i < n; i++ {
    pix[i] = math.Pi * answer[i].X
  }
  for i := 0; i < n; i++ {
    answer[i].Y = math.Sin(pix[i]) / pix[i] + 0.1 * answer[i].X + normalRand(1.0, 0.05)
  }

//====================================================
  // Graph Setting

  // Create a new plot, set its title and axis labels
  p, err := plot.New()
  if err != nil {
    panic(err)
  }
  p.Title.Text = "Plotinum Sample"
  p.X.Label.Text = "X"
  p.Y.Label.Text = "Y"
  p.Add(plotter.NewGrid())

  // Make a scatter plotter and set its style
  // Make a line plotter with points and set its style.
  lpLine, lpPoints, err := plotter.NewLinePoints(answer)
  if err != nil {
    panic(err)
  }
  lpLine.Color = color.RGBA{G: 255, A: 255}
  lpPoints.Shape = plot.PyramidGlyph{}
  lpPoints.Color = color.RGBA{R: 255, A: 255}

  // Add data and legend
  p.Add(lpPoints)
  p.Legend.Add("observed points", lpPoints)

  // Save the plot to a PNG file.
  if err := p.Save(4, 4, "sample.png"); err != nil {
    panic(err)
  }
}

Result

plotinum-result

未分類 recent post

  1. Install sbt 1.0.0 and run sample template

  2. Visualization of Neural Network and its Train…

  3. [Machine Learning]Created docker image includ…

  4. [Node.js]How to write batch script with Node.…

  5. [Hive]Get top n items for each category

関連記事

PAGE TOP