Ruby/Tk で簡単なグラフを描く

Ruby/Tk の描画機能を使って、簡単なグラフを描いてみました。

simple_graph

require 'tk'

class Graph
  Width = 400; Height = 400
  Ox = Width / 2; Oy = Height / 2  #原点
  
  def self.canvas
    @i = new
  end
  
  def self.draw(&b)
    @i.draw(&b)
  end
  
  def initialize
    TkRoot.new do
      title("simple graph")
    end
    @canvas = TkCanvas.new do
      width(Width); height(Height)
      background("lightcyan")
      pack
    end
    line(-200, 0, 200, 0, 'black')
    line(0, 200, 0, -200, 'black')
  end
  
  def line(x1, y1, x2, y2, color = 'red')
    return if (x1 < -200 || x1 > 200 || y1 < -200 || y1 > 200 || 
      x2 < -200 || x2 > 200 || y2 < -200 || y2 > 200)
    TkcLine.new(@canvas, x1.tr_x, y1.tr_y, x2.tr_x, y2.tr_y, 'fill' => color)
  end
  
  def draw
    for x1 in -200..200
      begin
        y1 = yield(x1)
        x2 = x1 + 1
        y2 = yield(x2)
        line(x1, y1, x2, y2)
      rescue; next; end
    end
  end
end

class Numeric
  def tr_x; self + Graph::Ox; end
  def tr_y; Graph::Oy - self; end
end


Graph.canvas
Graph.draw {|x| x ** 2 / 100}
Graph.draw {|x| x ** 3 / 7000}
Graph.draw {|x| Math.sqrt(100 ** 2 - x ** 2)}
Graph.draw {|x| - Math.sqrt(100 ** 2 - x ** 2)}

Tk.mainloop

Graph.draw {|x| func(x)} で描画する関数を指定します。