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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.