Thursday, February 3, 2011

GNUPlot—Plotting is fun


This article explores the use of GNUPlot for scientific plotting, with examples.
While strings and pages of data seem cryptic, a plot reveals the entire data flow at a glance. Interpretation suddenly seems much easier. Understanding that maze of numbers is just a glance away. Scientists, mathematicians, engineers, statisticians etc. rely heavily on plots. While OriginLab, an expensive commercial plotting software, is heavily used among university researchers or those blessed with bulging purses, GNUPlot doesn’t lag behind, and is much used by scientists at the IITs, IIScs and universities. In fact, knowledge and skill in GNUPlot is one of the requirements for some of the posts for Senior Research Fellow at the IITs!(see, for example, http://academicjobs.in/jobs/vacancy-for-the-senior-project-associate-in-iit-kanpur/2010/08/26/). The fact that GNUPlot can be used along with applications like Octave makes it even more indispensable.
GNUPlot is a portable command-line driven graphing utility for Linux, MS Windows, OSX, and many other platforms. While the source code is copyrighted, it can be freely distributed. GNUPlot supports many types of plots in 2D and 3D, and can draw using lines, points, boxes, contours, vector fields, surfaces, and various associated text, besides Web scripting. And for those who think ‘that is all’, here are some more attributes of GNUPlot: It supports interactive screen terminals (with mouse and hot-key input), direct output to pen plotters or modern printers, and output to many file formats like EPS, fig, JPEG, LaTeX, metafont, PBM, PDF, PNG, Postscript, SVG etc.; an interactive terminal based on wxWidgets, and the creation of mouseable graphs for Web display using the HTML5 canvas element.
Installation
Users of Ubuntu and other Debian-based distributions will find GNUPlot in the repositories. Synaptic maybe the best way to install. For RPM-based operating systems like Fedora, OpenSuSE and Mandriva, get it fromhttp://www.rpmfind.net/linux/rpm2html/search.php?query=gnuplot. If you‘re one of those hard-core guys who prefer source tarballs, then get yours from http://sourceforge.net/projects/gnuplot/files/gnuplot/4.4.2/gnuplot-4.4.2.tar.gz/download.
Anyone with itchy fingers like me? Let’s immediately jump to some example of using GNUPlot. Open the terminal/Konsole, and type gnuplot. You should see the following:
nelson@nelson-desktop ~ $ gnuplot
G N U P L O T
Version 4.2 patchlevel 6
last modified Sep 2009
System: Linux 2.6.32-21-generic
Copyright (C) 1986 – 1993, 1998, 2004, 2007 – 2009
Thomas Williams, Colin Kelley and many others
Type `help` to access the on-line reference manual.
The gnuplot FAQ is available from http://www.gnuplot.info/faq/
Send bug reports and suggestions to
Terminal type set to ‘wxt’
gnuplot>
GNUPlot in action
Example 1
We all know what a sine function looks like. Type in the following at the gnuplot prompt, and press Enter:
gnuplot> plot sin(x)
You will immediately see the sine plot popping up in a separate window. GNUPlot will auto-scale the axes to include all the data, and take ‘x’ as a variable.
Example 2
Let us plot the function y=cos(x)*x3. Type, at the GNUPlot prompt, the following:
gnuplot> plot cos(x)*(x**3)
Note: x3 is written as (x**3).
Though correct, the graph doesn’t seem to reveal the exact nature of the function. Redo it as follows:
gnuplot> set xrange [0:350]
gnuplot> set samples 5000
gnuplot> plot cos(x)*(x**3)
Interpretation:
  • Line 1: sets the x axis range from 0 to 350.
  • Line 2: sets the number of samples to 5000. Without this line, GNUPlot would evaluate the function at a fewer number of points, giving rise to a distorted wave.
  • Line 3: could also be written as gnuplot>replot.
Figure 1: Plot of the function y=cos(x)*x3
Figure 1: Plot of the function y=cos(x)*x3
As with all plots, we would like to save our work with all parameter settings, constant definitions etc. and the plot. Here is what you should do:
gnuplot> save “cosfunc.plt”
gnuplot> set terminal postscript eps enhanced color
Terminal type set to ‘postscript’
Options are ‘eps enhanced defaultplex \
leveldefault color colortext \
dashed dashlength 1.0 linewidth 1.0 butt \
palfuncparam 2000,0.003 \
“Helvetica” 14 ‘
gnuplot> set output ‘cosfunc.eps’
gnuplot> replot
gnuplot>
Interpretation:
  • Line 1: save “cosfunc.plt” will save your work in a file named cosfunc.plt, which can be edited using an ASCII editor like gedit or kwrite. ‘plt‘ implies “plot”.
  • Line 2: Sets the output to Postscript format.
  • Line 3: Most research publication work in Indian and foreign journals requires figures in EPS (Postscript). This line does exactly that. These EPS figures will be saved in the current working directory, and can be opened in GIMP and saved in JPG format, or whatever format you require that GIMP supports.
You can exit GNUPlot by typing:
gnuplot>exit
You can open an existing ‘plt‘ file with:
gnuplot> load ‘filename.plt’
Customising ticks, labels and titles
GNUPlot allows the setting of ticks (scale markings on the axes) with the ‘set xtics‘ and ‘set ytics‘ commands, with this sample syntax: gnuplot> set xtics , , . The format to set labels on the x axis, y axis and z axis (in case of 3D plots) are:
gnuplot> set xlabel ‘x-axis’
gnuplot> set ylabel ‘y-axis’
gnuplot> set zlabel ‘z-axis’
Similarly for the title of the graph, use the ‘set title‘ command:
gnuplot> set title ‘my-title’
Example 3
gnuplot> plot sin(x)
gnuplot> set ytics -1,0.1,1
gnuplot> set xtics -10,2,10
gnuplot> set xlabel ‘x-axis’
gnuplot> set ylabel ‘y-axis’
gnuplot> set title ‘SINE-PLOT’
gnuplot>replot
Figure 2 : Sine Plot with customised ticks,labels and title.
Figure 2 : Sine Plot with customised ticks,labels and title.
If you would like to change the font-size and/or font colour of your Postscript output, use the following syntax:
set terminal postscript {} {enhanced | noenhanced}
{color | monochrome} {solid | dashed}
{}
{””} {}
Here:
  •  is `landscape`, `portrait`, `eps` or `default`.
  • `solid` draws all plots with solid lines, overriding any dashed patterns.
  •  is `defaultplex`, `simplex` or `duplex`. (”Duplexing” in Postscript is the ability of the printer to print on both sides of the same page—don’t set this if your printer can’t do it).
  • `enhanced` activates the “enhanced Postscript” features (subscripts, superscripts and mixed fonts);
  • `”“` is the name of a valid Postscript font; and `` is the size of the font in Postscript points.
  • `default` mode sets all options to their defaults: `landscape`, `monochrome`, `dashed`, `defaultplex`, `noenhanced`, “Helvetica” and 14pt.
The default size of a Postscript plot is 10 inches wide and 7 inches high. You can change the size with the ‘set size width, height‘ command.
Plotting a data set with multiple columns
Rarely would one find a data set with only a single column of data. Let us consider a data set with three columns, with a blank space between columns, as follows (Data Set 1):
A B C
1 1 0.120373
2 2 0.898681
3 4 1.568595
4 9 2.049314
5 16 2.123498
Copy the data set into an ASCII editor, hash the first line, and save in your home directory as ‘data1‘. To obtain the plot using columns 1 and 2 and column 1 and 3, use:
gnuplot> plot “data1″ using 1:2 with lines, “data1″ u 1:3 with lines
In case of multiple data sets, you can use the following, with data sets separated by commas:
gnuplot> plot ‘dataset1′,’dataset2′,’dataset3′
Plotting with Errorbars
Experimental work always turns up errors—either instrumental, human or otherwise. The quality of work depends on the smallness of errors. In this case, the third column of a data set, such as the ‘C’ column in Data Set 1, should consist of the errors.
gnuplot> plot “data1″ with yerrorbars
gnuplot> plot “data1″ u 1:2 with lines, ‘data1′ with yerrorbars
Here, we have used error bars parallel to the y axis. We could also use error bars in the x direction, with ‘xerrorbars‘.
Plotting in Polar/Parametric
Here, t is taken as the variable for curves, and u/v for surfaces. Type in the following:
gnuplot> set polar
gnuplot> set grid polar
gnuplot> set samples 5000
gnuplot> plot 1+cos(t)/t,t
gnuplot> set parametric is to be used for parametric equations
Figure 3: The polar plot of 1+cos(t)/t, t
Figure 3: The polar plot of 1+cos(t)/t, t
Plotting in 3D
2D plots are fantastic, but 3D plots look fabulous. You just need to replace ‘plot‘ with ‘splot‘ to get a 3D plot, in the simplest case. However, getting detailed plots requires much typing at the GNUPlot prompt, and is the biggest let-down. The easier way out would be to type all the commands using an ASCII editor, and load the file at the prompt. Open gedit/kwrite/kate and type in the following:
set style data lines
set parametric
set view 60, 60, 1, 1
set xlabel ’x-axis’
set ylabel ’y-axis’
set zlabel ’z-axis’
set ztics -1,0.25,1
set title ‘MY PLOT’
#set pm3d implicit at s
#set xyplane at 0
#set mapping spherical
splot u,u+v,sin(0.5*(u+v))
set terminal postscript eps enhanced color
set output ‘myplot.eps’
replot
The ‘set view , , , ‘ format allows the user to set rotations about the x- and z-axis respectively, as well as the scale of the graph. Save the file as ‘myplot‘. Now, at the GNUPlot prompt, type:
gnuplot> load ‘myplot’
You will see that your plot is also saved in EPS. Use GIMP to covert it into your desired format.
Remove the # marks from the above script, one at a time, run the script, and observe the output. You will need to quit GNUPlot before you load the script again, to see the changes.
Figure 4: 3D Plot
Figure 4: 3D Plot
Figure 5: 3D Plot in colour
Figure 5: 3D Plot in colour
Finally
What has been covered should take you through most plotting needs. But GNUPlot can do much more. You can have text in colour, plot with cylindrical and spherical coordinates, use animations, plot mathematical functions, do curve-fitting, and a whole lot more. All this makes GNUPlot the desired plotting application. Check outhttp://gnuplot.sourceforge.net/demo/index.html for more.

No comments: