Last Updated: September 09, 2019
·
7.689K
· avgp

Use gnuplot to plot data in Ruby

If you need a way to plot some data with Ruby you should consider Gnuplot as a possibility. It allows you to output different file types (for example png, svg or pdf) and has a wide variety of scientific operations.

For more on Gnuplot checkout the manual

To install GnuPlot on OSX, you can just run

$ brew install gnuplot

and you're set.

For ruby there is a GnuPlot gem but I had the issue that it didn't output any file of any type, so I chose the manual way of passing in the commands directly to GnuPlot.

In my example below I'm extracting the data to plot from a CSV file but it doesn't really matter where it comes from. Put it in an array and you'll be fine.

require 'csv'
require 'open3'

data = CSV.read("data.csv", {:col_sep => "\t"})
data.collect! { |item| item[4].to_f} # extract a field value and parse to float
data.shift # removes the header

gnuplot_commands = <<"End"
  set terminal png
  set output "plot.png"
  set xrange [0:#{data.size}]
  plot "-" with points
End
data.each_with_index do |y, x|
  gnuplot_commands << x.to_s + " " + y.to_s + "\n"
end
gnuplot_commands << "e\n"

image, s = Open3.capture2(
  "gnuplot", 
  :stdin_data=>gnuplot_commands, :binmode=>true)

With this, GnuPlot figures out the range of the Y-Axis for you (to match the data in the plot) and plots the data as individual points. You can also do lines and such, if you wish.
The output is found in plot.png in the current working directory.