Tech Tips

  1. プログラミング
  2. 1106 view

[Plotinum][Go]Go言語でグラフを書いてみる

Contents

概要

Plotinumというライブラリを使うことでGo言語でグラフを描画することが出来るらしい。
このライブラリを使ってグラフを描いて保存するプログラムを書いてみる。

インストール

以下のコマンドを叩くだけ。非常に簡単。
go get code.google.com/p/plotinum/...

サンプルプログラム

plotinum-target-func
ここに公式のサンプルがいくつか用意されている。
勉強がてら、本記事ではこれにならって、以下の関数のグラフを生成してみる。
ここでwはN(1, 0.05) (平均1で分散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)
  }
}

結果

plotinum-result
  【新品】【書籍・コミック コンピューター】基礎からわかるGo言語
価格:2,376円(税込、送料別)

プログラミングの最近記事

  1. PlatformIO IDE for VSCode を使用して VSCode で Ardu…

  2. ROS Docker イメージで発生した GPG error の解消方法

  3. Streamlit で訪れた国を色づけした世界地図を作成できるアプリケーションを作成してみ…

  4. M5Stack Core2 for AWS – ESP32 IoT開発キットで…

  5. D3.js v7 で点・線・テキスト・ツールチップ・ズームを設定する方法

関連記事

PAGE TOP