Ruby Gnuplot - Utility library to aid in interacting with GNUPLOT

History and Background

GNUPLOT is a program that has a rich language for the generation of plots. It has a unique place in academia as it was one of the first freely available programs for plot generation. I started using GNUPLOT over 10 years ago while pursuing my Master’s degree in Physics and have been using it actively ever since.

Version 0.9

My first attempt at a Ruby interface to GNUPLOT was an object interface encapsulating GNUPLOT language. This was taken directly from the Python GNUPLOT interface. In spite of my being very familiar with GNUPLOT and Ruby and being the author of the RGnuplot package, I found it non-intuitive to use the RGnuplot package. I found myself constantly looking at the code to figure out what I needed to do. This was not sufficient and did not sit well.

Version 1.0

The second attempt at a Ruby interface was to do absolutely nothing but use Ruby’s built in string manipulation methods. This meant that I could simply use my knowledge of GNUPLOT without having to worry about objects. While in some ways an improvement over version 0.9, it still did not sit well with me.

Version 2.0

After attending RubyConf 2004 I was inspired by Rich Kilmer’s use of Ruby to implement domain specific languages. That is the current implementation of Gnuplot and quite probably the one that I’ll stick with for some time. This version combines the direct mapping of the GNUPLOT language without wrapping with the Ruby syntax and mechanism of adding methods to existing classes to interface Ruby objects with GNUPLOT.

Setup

Version 2.2

If the gnuplot command is in your path then there is no required setup. If the GNUPLOT executable for your system is called something other than simply gnuplot then set the RB_GNUPLOT environment variable to the name of the executable. This must either be a full path to the GNUPLOT command or an executable filename that exists in your PATH environment variable.

Ruby Gnuplot Concepts

GNUPLOT has a very simple conceptual model. Calls to set are made to set parameters and either plot or splot is called to generate the actual plot. The dataset to be plotted can be specified in a number of ways, contained in a separate file, generated from a function, read from standard input, or read immediately after the plot command.

The object model for the Ruby Gnuplot wrapper directly mimics this layout and flow. The following are the standard steps for generating a plot:

  • Instantiate a Gnuplot::Plot or Gnuplot::SPlot object and set parameters by GNUPLOT variable name.

  • Instantiate Gnuplot::DataSet objects and attach Ruby objects containing the data to be plotted to the data set.

  • Attach properties that modify the plot command using the modifier name.

  • Send the Plot/SPlot object to a GNUPLOT instance for plotting.

The version 2.0 interface makes heavy use of blocks leading to very readable code.

Gnuplot.open

Instantiates a new GNUPLOT process. The path to the executable is determined using the Gnuplot.which command. If a block is given to the function the opened process is passed into the block. This mimics the most common usage of the File.open method.

Gnuplot::Plot.new, Gnuplot::SPlot.new

Create a new Plot or SPlot object. DataSets are attached to the object to specify the data and its properties. If a block is given to the function, the plot object is passed into the block.

Gnuplot::DataSet.new

Associates a Ruby object containing the data to plot with the properties that will be passed to the plot command for that data set. Any Ruby object can be associated with a DataSet as long as it understands the to_gplot method.

to_gplot

Within GNUPLOT, plot data is read in very simple formats. The to_gplot method is expected to write the data of the object in a format that is understandable by GNUPLOT. One of the many great things about Ruby is that methods can be added after the original declaration. The Gnuplot module defines the to_gplot method on the classes Array and Matrix. Simply define a to_gplot method on your own class to tie the class into gnuplot.

Examples

Simple sine wave

The following example simply plots the value of sin(x) between the ranges of -10 and 10. A few points to notice:

The code uses nested blocks to construct the plot. The newly created object is passed to the block so it can be modified in place.

Each of the GNUPLOT plot variables is modified using the variable name as a method name on the plot object or on the data set object. The wrapper also takes care of the single quoting that is required on some of the variables like title, ylabel, and xlabel.

The plot object simply has an array of Gnuplot::DataSet objects. The constructor initializes this empty array before yielding to the block. This method uses the << operator to add the DataSet to the plot.

When the plot block ends, if an IO object is given to the Gnuplot::Plot constructor, the plot commands will be written to the IO object. Any object can be passed to the constructor as long as it understands the << operator.

Gnuplot.open { |gp|
  Gnuplot::Plot.new(gp) { |plot|

    plot.xrange '[-10:10]'
    plot.title  'Sine Wave Example'
    plot.xlabel 'x'
    plot.ylabel 'sin(x)'

    plot.data << Gnuplot::DataSet.new('sin(x)') { |ds|
      ds.with = 'lines'
      ds.linewidth = 4
    }

  }
}

Plotting discrete points

Array data can be plotted quite easily since Arrays have a defined Array#to_gplot method.

Simply pass an array of data to the constructor of the Gnuplot::DataSet object or set the data property of the DataSet. In this example, because there are two arrays, each array will be a single column of data to the GNUPLOT process.

Also, this example uses the Gnuplot.plot convenience method which wraps the calls to Gnuplot.open and Gnuplot::Plot.new.

Gnuplot.plot { |plot|
  plot.title  'Array Plot Example'
  plot.xlabel 'x'
  plot.ylabel 'x^2'

  x = (0..50).map { |v| v.to_f }
  y = x.map { |v| v ** 2 }

  plot.data << Gnuplot::DataSet.new([x, y]) { |ds|
    ds.with = 'linespoints'
    ds.notitle
  }
}

Multiple Data Sets

As many data sets as are desired can be attached to a plot. Each of these can have their own plot modifiers. Notice in this example how the data array is set through the Gnuplot::DataSet#data convenience method instead of using the << operator.

Also in this example, the commands are not written to the GNUPLOT process but are instead written to a File called gnuplot.dat. This file can later be run directly by a GNUPLOT process as it contains only the GNUPLOT commands.

Gnuplot.plot_to('gnuplot.dat') { |plot|
  plot.xrange '[-10:10]'
  plot.title  'Sin Wave Example'
  plot.xlabel 'x'
  plot.ylabel 'sin(x)'

  x = (0..50).map { |v| v.to_f }
  y = x.map { |v| v ** 2 }

  plot.data('sin(x)') { |ds|
    ds.with = 'lines'
    ds.title = 'String function'
    ds.linewidth = 4
  }

  plot.data([x, y]) { |ds|
    ds.with = 'linespoints'
    ds.title = 'Array data'
  }
}

You can also add arbitrary lines to the output:

plot.arbitrary_lines << 'set ylabel "y label" font "Helvetica,20"'

# or more conveniently
plot << 'set ylabel "y label" font "Helvetica,20"'