Saturday, June 02, 2007

Ruby: Plotting with gnuplot in Mac X

To plot in Ruby, one can use rgplot interface to gnuplot. To install it, just download gnuplot-gem and install bysudo gem install ./gnuplot-2.2.gem
If you have gnuplot already installed it is good, if not install it bysudo port install gnuplot.
Assuming that everything went well, one can now plot and save figures using Ruby.
Simple example of Ruby code that plots simple data and saves (do not display) it to png file.
#!/usr/bin/env ruby
#testGnuplot.rb
require 'rubygems'
require 'gnuplot'



outFname='graph.png'
xData=[1, 2, 3, 4,5]
yData=[2, 3 ,4, 2,3]

#xData=(0..10).collect { |v| v.to_f }
#yData= xData.collect { |v| v ** 2 }



Gnuplot.open do |gp|
Gnuplot::Plot.new( gp ) do |plot|
plot.output outFname
plot.terminal 'png'
plot.title "Array Plot Example"
plot.ylabel "y"
plot.xlabel "x"

x= xData
y= yData

plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds|
ds.with = "linespoints"
ds.notitle
end

end
end

This is especially useful when one want to plot a lot of figures contained in a data file. Of corese, this is the simples example, and more complicated things require to do some experimenting before desired plots are obtained. Nonetheless, this is good start.


To plot two data on one graph and to save it as png one can do as below:

#!/usr/bin/env ruby
#test.rb
require 'rubygems'
require 'gnuplot'
outFname='graph.png'
xData=[1, 2, 3, 4,5]
yData=[2, 3 ,4, 2,3]
yData2=[1, 2 ,3, 3,4]

Gnuplot.open do |gp|
Gnuplot::Plot.new( gp ) do |plot|
plot.output outFname
plot.terminal 'png'
plot.title "Array Plot Example"
plot.ylabel "y"
plot.xlabel "x"

x= xData
y= yData

plot.data =[ Gnuplot::DataSet.new( [x, y] ) do |ds|
ds.with = "linespoints"
ds.notitle
end,
Gnuplot::DataSet.new( [xData, yData2] ) do |ds|
ds.with = "linespoints"
ds.notitle
end
]

end

end

Results is (graph.png):

No comments:

Post a Comment