TweetFollow Us on Twitter

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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.