An Introduction to Gnuplot
**Volume Number: 26**

Issue Number: 02

Column Tag: math

# An Introduction to Gnuplot

## what Gnuplot is and how to use it

*by Mihalis Tsoukalos*

### Introduction

This article is going to present to you a very useful tool called Gnuplot. Gnuplot is copyrighted but freely distributed. There are versions of Gnuplot for UNIX, IBM OS/2, MS Windows, DOS, Macintosh, VMS, Atari and many other platforms.

There is also a Python module for using Gnuplot inside of Python code. The library is called py-gnuplot, and will be introduced in this article.

### What is Gnuplot?

Gnuplot is a command line tool that was initially developed in order to allow scientists and students to visualize mathematical functions and data. It now supports web scripting and integration as a plotting engine for third-party applications like Octave.

Gnuplot can draw many types of plots in either 2D or 3D. It supports drawing using lines, points, vector fields, surfaces, boxes, and contours. You can also add text in its output.

It also supports output in many different file formats including eps, fig, jpeg, LaTeX, METAFONT (invented by Donald Knuth the creator of TeX), pdf, png, postscript, etc.

I will have to tell you that if you want to become an advanced Gnuplot user, you must start reading its official documentation. In my system, the gnuplot.pdf file (the official manual) is located inside the /opt/local/share/doc/gnuplot directory, but location will depend on your installation method.

### Some simple examples

First of all, let me review the version of Gnuplot that I am using. You can find that info by running the following command from Terminal.app (or a similar application):

$ gnuplot -V
gnuplot 4.2 patchlevel 5

An analogous command will let you you find out the Python version that is installed into your Mac-Python will be used later on in this article. In my system, I had the following output:

$ python -version
Python 2.5.2

The first example that I will demonstrate you,will draw the *sin(x)*cos(x)* function. You can do this by running the following command in the gnuplot command line. This can be done after running gnuplot from a Terminal.app window:

gnuplot> plot sin(x)*cos(x)

After pressing the return key, an AquaTerm output window will appear (AquaTerm was likely installed by your port manager, like MacPorts. You can retrieve it manually from http://aquaterm.sourceforge.net/). You can see the generated output in Figure 1.

**
**Figure 1: drawing the sin(x)*cos(x) function

Now, we will try to beautify the output-that is pretty basic and simplistic-and maybe add some text to it.

First, if you remember your Math classes, it doesn't make sense to use -10 and +10 as our graph boundaries when dealing with trigonometric functions-it would be better to use -2*pi and +2*pi instead. To do this, the following two commands must be given:

gnuplot> set xrange [-2*pi:2*pi]
gnuplot> replot

As you can see, the "set xrange" command defines the graph boundaries, but the "replot" command is needed for Gnuplot to sketch the new output.

Please note that the AquaTerm output is updated automatically, so please do not close the AquaTerm application-this will make your life a lot easier. Also note that the numerical value of pi is proximately 3.14. The new output can be seen in Figure 2.

**
**Figure 2: using -2*pi and +2*pi as our x-axis boundaries

The next thing that we would like to do is add our own text to the output. Figure 3 shows the output that is produced by executing the following gnuplot commands:

gnuplot> set title "An example for MacTech"
gnuplot> set xlabel "x-axis: from -2*pi to +2*pi"
gnuplot> set ylabel "Setting the y-axis label"
gnuplot> replot

**
**Figure 3: adding some text to the output

Now, grid lines are going to be added to our output (you can see the produced output in Figure 4). The following gnuplot commands must be given:

gnuplot> set xtics ("0" 0, "-180" -pi, "-90" -pi/2, "90" pi/2, "180" pi)
gnuplot> set ytics ("0" 0, "0.5" 0.5, "-0.5" -0.5)
gnuplot> set grid
gnuplot> replot

**
**Figure 4: adding gridlines to the gnuplot output

### More advanced examples

This part of the article will present you with some more advanced ways of using gnuplot. After all, gnuplot is a scientific tool.

Plotting more than one function in the same output

Let's say that you want to see two functions in the same output in order to compare them. Gnuplot can help you do this. The following command explain how:

gnuplot> plot x*x, 1/(x*x)

As you see, all you have to do is separate the two functions with a comma. If you want to smarten the output, you can give the following command:

gnuplot> plot x*x, 1/(x*x) with filledcurves fs 0

You can see the final output in Figure 5 and you can easily understand that the "with filledcurves fs 0" does all the work for us-it fills the second function with gray color. Please note that gnuplot has a built-in help system. You can say, for example, help plot and get useful information about the plot command-just try it!

**
**Figure 5: plotting two functions

Plotting many functions in multiplot mode

Sometimes it is preferred to show multiple graphs side-by-side. Gnuplot gives you the choice of plotting multiple graphs side-by-side on the same output screen. The key point for doing this is the "set multiplot" command. If you give this command the prompt will change from "gnuplot" to "multiplot".

You can see the output of the following example in Figure 6:

gnuplot> set xrange [-1:1]
gnuplot> set size 1,1
gnuplot> set origin 0,0
gnuplot> set multiplot
multiplot> set size 0.5,0.5
multiplot> set origin 0,0.5
multiplot> plot (x*x)
multiplot> set size 0.5,0.5
multiplot> set origin 0.5,0.5
multiplot> plot sin(x)
multiplot> set size 0.5,0.5
multiplot> set origin 0,0
multiplot> plot (1/x)
multiplot> set size 0.5,0.5
multiplot> set origin 0.5,0
multiplot> plot (x*x*x)
multiplot> unset multiplot
gnuplot> reset
gnuplot>

**
**Figure 6: using multiplot mode

Now, lets talk about the commands that were typed in order to get the output of Figure 6. The plot and xrange commands were already shown earlier. Also, as we said before, the "set multiplot" command is needed in order to enter the multiplot mode. Similarly, the "unset multiplot" command is used for exiting multiplot mode. The reset command causes all graph-related options that can be set with the set command to take on their default values. The rest of the commands (size, origin) position each graph in its place and make it take just a quarter of the screen. Again, if you want more information about a command you should see the help pages.

Plotting data files

Imagine that you have a file that contains groups of data points that you want to plot. Well, gnuplot can help you again! The following commands illustrate what gnuplot shows when plotting a valid data file-nothing, it just plots it!- as well as when trying to parse an erroneous data file. For an erroneous data file, gnuplot prints an error message telling us the line that the first error occurred-this does not indicate that the rest of the file is fine, just that there is at least one error. The compatible data file gets plotted without problems and you can see its output in Figure 7.

gnuplot> plot 'dataBad'
^
Bad data on line 325
gnuplot> plot 'data'

**
**Figure 7: using external data files when drawing a graph

The format of the "data" file is as follows but many other formats are allowed:

$ head data
1024 38
1025 5
1026 18
1027 16
1028 20
1029 6
1038 5
1048 4
1049 16
1051 4

### Using Gnuplot and Python

This part of the article will present py-gnuplot-the Python interface to the gnuplot plotting program.

The first thing you should do is to install py-gnuplot. I used MacPorts (there is also a fink version of the package) version of py-gnuplot-the simple installation process was as follows:

$ sudo port install py25-gnuplot
--> Fetching python25
--> Attempting to fetch Python-2.5.2.tgz from http://www.python.org//ftp/python/2.5.2/
--> Verifying checksum(s) for python25
--> Extracting python25
--> Applying patches to python25
--> Configuring python25
--> Building python25 with target all libpython2.5.dylib
--> Staging python25 into destroot
--> Installing python25 2.5.2_5+darwin_9
--> Activating python25 2.5.2_5+darwin_9
[output removed for brevity]
--> Staging py25-gnuplot into destroot
--> Installing py25-gnuplot 1.7_0
--> Activating py25-gnuplot 1.7_0
--> Cleaning py25-gnuplot

So, we now have both Python 2.5 and py-gnuplot 1.7 installed. It now is time to start using them.

I would first like to tell you that in this part of the article, the output of each Python script is going to be saved in a file and will not be displayed on screen. I found this the most practical usage for a script.

A simple example is shown in Listing 1:

Listing 1: gp-example.py

#! /usr/bin/env python
# Programmer: Mihalis Tsoukalos
# Date: Friday 10 July 2009
#
# Description: Example of using py-gnuplot
#
import Gnuplot
gp = Gnuplot.Gnuplot(persist=1)
gp('set term png')
gp('set output "mactech.png"')
g5 = Gnuplot.Func('sin(x)/x', title='Plotting a function with py-gnuplot')
gp.plot(g5)

The output, which is a file called mactech.png, is shown in Figure 8. The key points of the Python script are:

The "import Gnuplot" command that load the correct Python module

The "gp.plot(g5)" command that actually plots the graph

The "gp('set term png')" and "gp('set output "mactech.png"')" commands that define the output file format and filename.

**
**Figure 8: plotting a function using Python and py-gnuplot

Please note that you should read the py-gnuplot documentation in order to better understand and utilize it.

The last example of this article is going to be a 3D graph. The Python code for creating Figure 9 is the following:

#! /usr/bin/env python
# Programmer: Mihalis Tsoukalos
# Date: Friday 10 July 2009
#
# Description: Example of using py-gnuplot
#
# This script is a modified version of existing Python code
# from the demo.py file that can be found inside
# the /opt/local/lib/python2.5/site-packages/Gnuplot directory
#
from Numeric import *
import Gnuplot, Gnuplot.funcutils
gp = Gnuplot.Gnuplot(persist=1)
gp('set term png')
gp('set output "3Dplot.png"')
# set up x and y values at which the function will be tabulated:
x = arange(50)/2.0
y = arange(25)/10.0 - 1.5
xm = x[:,NewAxis]
ym = y[NewAxis,:]
m = (cos(xm) + 0.1*xm) - ym**2
gp('set parametric')
gp('set data style lines')
gp.title('An example of a 3D plot!')
gp.xlabel('x')
gp.splot(Gnuplot.GridData(m,x,y, binary=0))

You may find it difficult but, after reading it more carefully, you will understand how simple and elegant this is.

**
**Figure 9: doing 3D plots with py-gnuplot

### Summary

Gnuplot is a very handy and highly customizable tool. This article is just the beginning of learning it. The excellent on-line help of gnuplot can assist you go further.

By combining it with Python-or your favorite scripting language-you will get the benefits of a scripting language in conjunction with a great tool!

As always, the key to success is practicing, more practicing and even more practicing!

### Web Links and Bibliography

Gnuplot homepage: http://www.gnuplot.info/

Gnuplot development: http://sourceforge.net/projects/gnuplot/

Gnuplot Python package: http://gnuplot-py.sourceforge.net/

Mihalis Tsoukalos lives in Greece with his wife Eugenia and enjoys digital photography and writing articles. He is the author of the “Programming Dashboard Widgets” eBook. You can reach him at tsoukalos@sch.gr.