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

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'
^
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.

```#! /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!

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.

Community Search:
MacTech Search:

X Lossless Decoder 20141129a - Encode, t...
X Lossless Decoder (XLD) is a tool for OS X that is able to decode/convert/play various 'lossless' audio files. The supported audio files can be split into some tracks with cue sheet when decoding... Read more
Mariner Write 3.9.4 - Light-weight and s...
Mariner Write is your Mac OS go-to word processing tool! Professional writer, educator or student, Write has all the functionality you need for that important letter, technical paper or research... Read more
Google Chrome 45.0.2454.85 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Apple Pro Video Formats 2.0.2 - Updates...
Apple Pro Video Formats brings updates to Apple's professional-level codes for Final Cut Pro X, Motion 5, and Compressor 4. Version 2.0.2: Includes support for the following professional video codecs... Read more
Apple Final Cut Pro X 10.2.2 - Professio...
Apple Final Cut Pro X is a professional video editing solution.Completely redesigned from the ground up, Final Cut Pro adds extraordinary speed, quality, and flexibility to every part of the post-... Read more
Apple Compressor 4.2.1 - Adds power and...
Compressor adds power and flexibility to Final Cut Pro X export. Customize output settings, work faster with distributed encoding, and tap into a comprehensive set of delivery features. Powerful... Read more
Apple Motion 5.2.2 - Create and customiz...
Apple Motion is designed for video editors, Motion 5 lets you customize Final Cut Pro titles, transitions, and effects. Or create your own dazzling animations in 2D or 3D space, with real-time... Read more
Posterino 3.2.2 - Create posters, collag...
Posterino offers enhanced customization and flexibility including a variety of new, stylish templates featuring grids of identical or odd-sized image boxes. You can customize the size and shape of... Read more
A Better Finder Rename 10.00b1 - File, p...
A Better Finder Rename is the most complete renaming solution available on the market today. That's why, since 1996, tens of thousands of hobbyists, professionals and businesses depend on A Better... Read more
CrossOver 14.1.6 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more

## Latest Forum Discussions

Spirit Hunter is an Upcoming Collectible...
Boomlagoon, the team behind hybrid CCG/runner Monsu, has announced their newest project: a collectible card game/action RPG named Spirit Hunter. [Read more] | Read more »
Zen Brush 2 (Entertainment)
Zen Brush 2 1.0 Device: iOS Universal Category: Entertainment Price: \$2.99, Version: 1.0 (iTunes) Description: Zen Brush 2 is a drawing app focused on the strong yet beautiful feel of the East Asian ink brush. | Read more »
NetNewsWire (News)
NetNewsWire 4.0.0 Device: iOS iPhone Category: News Price: \$3.99, Version: 4.0.0 (iTunes) Description: Follow the Web NetNewsWire 4, completely written from the ground up for iPhone. NetNewsWire is the best way to keep up with the... | Read more »
Huzzah! Farming Simulator 16 Supports Cl...
As though it weren't difficult enough to resist the siren call of Farming Simulator 16, now it's been updated with cloud saves - so you can jump between devices without missing any of that precious crop-harvesting time. [Read more] | Read more »
Don't Starve: Pocket Edition Finall...
I've made no effort to hide my enjoyment of Don't Starve: Pocket Edition, but I will admit I was a tiny bit disappointed that it was only available for the iPad. Well nuts to that, because Klei Entertainment has made it universal! [Read more] | Read more »
Goat Simulator Wasn't Enough? Then...
If you just didn't get enough goat in Goat Simulator - or if you've been wanting to play a simulated MMO as a microwave - then you're in luck! Goat Simulator MMO Simulator is out now, and it's a game about simulated goats in simulated MMOs. Plus... | Read more »
You Can Play Madfinger Games' Unkil...
KORG iELECTRIBE for iPhone (Music)
KORG iELECTRIBE for iPhone 1.0.1 Device: iOS iPhone Category: Music Price: \$9.99, Version: 1.0.1 (iTunes) Description: ** 50% OFF Special Launch Sale - For a Limited Time **The ELECTRIBE reborn in an even smaller form A full-fledged... | Read more »
Toca Life: City Just Got a Bunch of New...
Toca Life: City is Toca Boca's most popular app (number 1 in 47 different countries, apparently), and it's just had an update that adds a bunch of new content. [Read more] | Read more »
My Country 3D is More About Cities than...
My Country 3D is an upcoming city builder from Game Insight that looks pretty decent - although the name seems a tad out of whack for a city builder. Ah well, it is what it is. [Read more] | Read more »

## Price Scanner via MacPrices.net

DEVONthink and Co. 40% Off For Students And E...
Students and teachers are either preparing for the new semester or are already back in school. And the better organized they are the easier it is for them to concentrate on what’s really important:... Read more
Labor Day Weekend Sale: MacBook Air for up to...
Best Buy has MacBook Airs on sale for up to \$150 off MSRP on their online store this weekend. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-... Read more
BassJump Subwoofer for MacBook Refreshed...
Twelve South has released a software update for BassJump, their portable subwoofer for Macbook. BassJump 3.0 has a radically redesigned interface, and the software refresh makes the BassJump... Read more
Near-Office Input Functionality Virtually Any...
Today Logitech introduced the Logitech K380 Multi-Device Bluetooth Keyboard and the Logitech M535 Bluetooth Mouse, giving users the freedom to work on any device, most anywhere. According to... Read more
College Student Deals: Additional \$100 off Ma...
Take an additional \$100 off all MacBooks and iMacs at Best Buy Online with their College Students Deals Savings, valid through September 4, 2015. Anyone with a valid .EDU email address can take... Read more
2.8GHz Mac mini available for \$988, includes...
Adorama has the 2.8GHz Mac mini available for \$988, \$11 off MSRP, including a free copy of Apple’s 3-Year AppleCare Protection Plan. Shipping is free, and Adorama charges sales tax in NY & NJ... Read more
It looks like we may not have to wait much longer to see what finally materializes as a new, larger-panel iPad (Pro/Plus?) Usually reliable Apple product prognosticator KGI Securities analyst Ming-... Read more
eFileCabinet Announces SMB Document Managemen...
Electronic document management (EDM) eFileCabinet, Inc., a hosted solutions provider for small to medium businesses, has announced that its SecureDrawer and eFileCabinet Online services will be... Read more
San Francisco’s WaterField Designs today unveiled their all-leather Cozmo 2.0 — an elegant attach laptop bag with carefully-designed features to suit any business environment. The Cozmo 2.0 is... Read more
Apple’s 2015 Back to School promotion: Free B...
Purchase a new Mac or iPad at The Apple Store for Education and take up to \$300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more

## Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Content Partner Engineer - *Apple* TV - App...
**Job Summary** The Apple TV team is looking for an experienced engineer with a passion for delivering first in class home entertainment solutions. The candidate will Read more
*Apple* Desktop Analyst - KDS Staffing (Unit...
…field and consistent professional recruiting achievement. Job Description: Title: Apple Desktop AnalystPosition Type: Full-time PermanentLocation: White Plains, NYHot Read more
*Apple* Retail - Multiple Customer Support P...
Job Description: Customer Support Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the Read more
*Apple* Desktop Analyst - KDS Staffing (Unit...
…field and consistent professional recruiting achievement. Job Description: Title: Apple Desktop AnalystPosition Type: Full-time PermanentLocation: White Plains, NYHot Read more