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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
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.