ファイルをまとめてgnuplotするRubyスクリプト
研究関連で「数値が1行ずつ記述されたテキストファイル」をまとめてグラフ化したかったので、Rubyからgnuplotを使って実現してみた。
準備
Ubuntu環境なので、aptitudeでgnuplotを入れる。
(x11環境も使いたい場合はgnuplot-x11を入れる。このままだとgnuplot-noxが入る。)
$ sudo aptitude install gnuplot
また、Rubyからgnuplotを使うためのgemを入れる。
$ sudo gem install gnuplot
スクリプト
hico-horiuchi/line_plot.rb · GitHub
require 'gnuplot' Gnuplot.open do |gp| Gnuplot::Plot.new(gp) do |plot| plot.term "postscript 16 color" plot.output ARGV.first + ".eps" plot.title ARGV.shift plot.xlabel ARGV.shift plot.ylabel ARGV.shift ARGV.each do |file| y = [] File.open(file).each_line do |line| y << line.to_f end x = (0..y.size - 1).collect {|v| v.to_i} plot.data << Gnuplot::DataSet.new([x, y]) do |ds| ds.with = "lines" ds.linewidth = 4 ds.title = file end end plot.grid end end
コマンドラインで指定したタイトルなどのオプションをshiftして、残りをファイルとして順に読み込む。
ファイルの内容を1行ずつ実数として配列に格納して、Yの値とする。
Xの値は、ファイルの行数(Yのデータ個数)に合わせて、0から順番に整数で振る。