Gnuplot tutorial
From Physics
Gnuplot Tutorial
By Dr R LindebaumContents 
Introduction
Gnuplot is a powerful plotting program which has many useful features. Both Linux and Windows version are available. This tutorial is aimed at helping students use gnuplot for their projects. This tutorial does not cover all the features of gnuplot, but rather a small selection of features that will hopefully be most useful for physics and computational physics students. It will only describe some options for commands, but if you want to do something more complicated, you can use the help system to learn about all the features of the commands. This tutorial is specifically for gnuplot 4.0, but should be useful for both earlier and later versions.
There is a fairly comprehensive help system in gnuplot. The general form of the help command is
help <topic>
for example
help plot
This will give help on this command and provide a list of subtopics at the end, which will look like
Subtopics available for plot: acsplines bezier binary csplines
You can now type in the subtopic, eg. bezier to get more information on how the to plot bezier curves. In Linux press q to get back to the command prompt. You can also get there in one step if you like with the command
help plot bezier
For many of the commands that I will discuss here, there are many more options that you can use than the ones I discuss. the use of help command will describe the command in full.
Interactive and batch modes
Gnuplot can be run either interactively, where you type in commands and gnuplot executes those commands as you type them. Interactive mode is started by typing gnuplot on the command line with no additional arguments. An example session is below.
gnuplot> set title "Graph of velocity versus time" gnuplot> set xrange[0:10] gnuplot> plot sin(x) gnuplot> quit 

Instead of typing the commands directly into gnuplot, you can put the commands in a text file. For example, the we could type the following list of commands in a editor and save them to a file say plot1.gnu
set title "Graph of velocity versus time" set xrange[0:10] plot sin(x) pause 1
Note the pause 1 command at end of this file, it prevents gnuplot from continuing until a key is pressed. It is useful in batch mode only as otherwise gnuplot would draw the plot then close down immediately without giving you time to view your plot. Now to create the plot one can simply start gnuplot with the name of the file on the command line, eg
gnuplot plot1.gnu
which draws the plot in a window and closes down after a key is pressed. If you still want to be able to type commands after the plot is made you could start it using the following commands:
gnuplot gnuplot> load 'plot1.gnu'
The benefit of saving the commands to a file, is that it is easy to recreate a plot later. If you are in interactive mode you can also do this by saving your plot to do this, after the plot command type
gnuplot> save 'plot1.gnu'
This creates the file plot1.gnu which contains all the commands to generate the plot that you have just generated. Note, this file is not a copy of the commands that you have typed, rather the commands necessary to generate the last plot that you made. It includes all the possible options to the commands. This makes the file big and quite hard to read.
Quickstart
Suppose you wish to plot the function x sin(1.2 x) on the range [0,7]. The following commands will produce the graph alongside.
set xrange[0:7] plot x*sin(1.2*x) 

All graphs have little meaning unless the axes have labels and the graph a title
set title 'Graph of velocity versus ' set xlabel 'Time/s' set ylabel 'Velocity/ms^{1}' set xrange[0:7] plot x*sin(1.2*x) 

Terminals and output
Gnuplot by default draws the plots you create onto the screen. Often you want to create a plot for inclusion in a document, gnuplot can do this as well. If you are using openoffice, there are two formats that you can use, either emf or png. To create a png file you must set the terminal type and the file to send the output to eg
set terminal png enhanced set ouput 'test.png'
Now when you execute the plot command, the png file is created and nothing goes to the screen. It is rather useful to use the enhanced version if the terminal. This allows you to create sub and superscripts, and change the fonts. For example x^{1}_{32} is produced with x^{1}_{32}. For more info about enhanced terminals type
help enhanced
To send the output back to the screen again use the commands
set term X11 enhanced set out
To make a better image in an openoffice document it is useful to make a large png file, and then use open office to shrink it to the size on the page that you want (The image may appear less sharp on screen, but it will print out better!). If you want a larger image you can append a large or giant to the terminal.
set terminal png enhanced large
Or if you want a specific size, for example 1024x768 which generates a good looking plot
set terminal png enhanced size 1024,768
Since the postscript terminal is one of the most used, it has the most features. Unfortunately Openoffice does not handle postscript files well, so one way to use a postscript terminal is to create an eps file by
set terminal postscript eps enhanced set out 'test.eps' plot sin(x)
Now in a bash shell use the pstoimg command to convert the postscript image to a png file form the command line type
bash# pstoimg scale 2 test.eps
This will create a file test.png which you can import into openoffice.
2D Plots (plotting curves)
Gnuplot can plot both analytic functions and data in data files. We will first look at some common commands that affect both.
Common commands
There are numerous options that you can set that will affect the overall look of the graph (Most work for 3D plots as well) Note that these commands have many more options, just the basic ones are used here. Type
help set xlabel
for example to get help on all the possible options for the xlabel.
Make a title  set title 'Graph of velocity versus time' 
Label x axis  set xlabel 'Time(s)' 
Label y axis  set ylabel 'Velocity(m/s\^2)' 
Adjust the tick marks  set xtics 0.1 
set ytics 0.1  
Adjust no. of minor tick marks  set mxtics 4 
Move the key  set key bottom left 
set key top right  
Change the key text  plot sin(x) title "new text" 
Remove the key  unset key 
Set plot aspect ratio  set size square 
:A wide plot  set size ratio 0.25 
:A narrow tall plot  set size ratio 2 
Adjust the xrange  set xrange[3:5] 
Adjust the lower xrange, upper auto  set xrange[3:*] 
Adjust the upper xrange, lower auto  set xrange[*:5] 
Use a logarithmic x axis  set logscale x 
Use a logarithmic y axis  set logscale y 
Draw a grid on major tics  set grid y 
2d plots
As we saw in the quickstart section above, we can easily create 2 dimensional plots. For example the commands below produce
set title 'Graph of velocity versus time' set xlabel 'Time/s' set ylabel 'Velocity/ms^{1}' set xrange[0.1:7] set mxtics 4 set grid set logscale y plot x*exp(x) title velocity 

Besides plotting functions, you can also plot data that is in a file. The file should contain columns of number separated by white space. Any line that starts with # is ignored so you can put comments in your file For example if the file data.dat contains
# time x y 0.000 2.345 0.0000 0.500 2,86 1,32 1.000 3.41 1.9 1.5 3.42 1.99 2.0 3.2 1.8
You can plot x versus time using
set title 'Graph of x versus time' set xlabel 'Time/s' set ylabel 'x/m' plot 'data.dat' using 1:2 title "x" 

Note the use of the using 1:2 which makes gnuplot use column 1 for the data on the horizontal axis and column 2 for the data on the vertical axis.
It is rather useful to be able to join the points with lines. Below we plot the third column versus the first column of data and draw lines between the points.
set title 'Graph of y versus time' set xlabel 'Time/s' set ylabel 'y/m' plot 'data.dat' using 1:3 title "y" with lines 

Gnuplot can also plot manipulated versions of the columns for example if we want to plot y*sin(t) versus x*sin(t) using the same table we could use
set title 'Graph of y*sin(t) versus x*t' set xlabel 'x*t/ms' set ylabel 'y*sin(t)/m' unset key plot 'data.dat' using ($2*$1):($3*sin($1)) with lp 

Note the if we want to compute a column the using parameter has the form using (....):(.....) where the things in the brackets are the function we must apply to the data. $1 refers to column 1, $2 to column 2 and so on. Also note the use of with lp at the end of the plot which plots both the points and joins lines between them.
Arrows and labels
Sometimes It is useful to draw lines and arrows on a plot and put labels on them. This can be easily done with the set arrow and the set label commands. Examine the following plot
set title 'Graph of velocity versus time' set xlabel 'Time/s' set ylabel 'Velocity/ms^{1}' set xrange[0:7] set mxtics 4 set arrow 1 from 1.9,1.0 to 2.01,1.8 set label 1 "First max" at 1.8,1.0 right plot x*sin(x) title velocity 

The basic form of the set arrow command is
set arrow <tag> from x,y to x,y
Tag is just a reference tag for the arrow  use 1,2,3,4,... for successive arrows. By default, the coordinates used are the graph coordinates, but other options are available. The easiest way to get them is to click the middle mouse button at the end points of the arrow, which will print the coordinates at those points. It is also possible to append nohead to this command to just draw the line without the arrow head. There are more options to this command see
help set arrow
for more details
The basic form of the set label command is
set label <tag> "label text" at x,y <leftcenterright>
Again tag is a just a reference number to the label, At the end of the label we specify how to justify the text around the point specified in the at x,y. Left means the left side of the text is at that point, right means the right side is at that point and center means it is centered on that point. Again there are many more options for these labels for setting fonts, colours, rotations etc. see
help set label
for more options.
3d Plots
Basics
It is also possible in gnuplot to plot functions of two variables, eg z=f(x,y). Or equivalently data files which represent such a function. The command to do this is splot which is like the plot command but wants a function of two variables.
set xrange[0:7] set yrange[1:5] splot exp(0.2*x)*cos(x*y)*sin(y) 

You can increase the number of lines in the plot with the set isosamples command.
set xrange[3:7] set yrange[1:5] set isosamples 30 splot exp(0.2*x)*cos(x*y)*sin(y) 

Data files require 3 columns, two for the x and y coordinates, and a z value which represents the height at that (x,y).. Ideally you want equispaced data which increases sequentially in one coordinate and then the other. At the end of one coordinate sequence put a single blank line. for example if the file test.dat contains
0 0 1 0 2 1.1 0 3 1.2 0 4 1.33 1 0 0.9 1 2 1.06 1 3 1.15 1 4 1.22 2 0 0.7 2 2 1.0 2 3 1.09 2 4 1.25
(note: the x and y coordinates can be real numbers too) then we can plot this data with the following
splot 'test.dat' title 'test' with lines 

Hidden lines
It is also possible to remove lines that would be hidden if the surface was not transparent. This can make complicated diagrams easier to understand
set xrange[3:7] set yrange[1:5] set isosamples 30 set hidden3d splot exp(0.2*x)*cos(x*y)*sin(y) 

Contours
It is also possible to draw contours on the plot. using the set contour <basesurfaceboth> eg
set contour surface
which makes gnuplot draw contours on the surface. the base option make the contours get drawn in the base, and both draws them in both places.
set xrange[3:4] set yrange[1:5] set isosamples 30 set hidden3d set key outside set contour both splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

Often one simply wants the contour plot as viewed from above to do this use
set view map unset surface
The unset surface prevents the surface from being drawn, as from above it is just a grid.
set xrange[3:4] set yrange[1:5] set isosamples 50 set view map unset sureface set hidden3d set key outside set contour base splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

Sometimes the automatic contour levels are not adequate. You can do many adjustments to the contour levels using the set cntrparam command. For example
set cntrparam levels 10
instructs gnuplot to try fit 10 contour levels in. It will not force it to use exactly 10, but rather it will choose appropriate levels so that there are nearly 10 levels. There are many other options see help cntrparam for more details.
set xrange[3:4] set yrange[1:5] set isosamples 50 set view map unset surface set hidden3d set key outside set contour base set cntrparam levels 10 splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

Colouration with pm3d
It is quite nice to colour shade the surfaces of plots with shades that depend on the height in the z direction. to do this use
set pm3d
set pm3d has a number of options which affect the appearances of the plots. For example
set xrange[2:2] set yrange[2:2] set isosamples 50 set pm3d unset surface set key outside splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

It is also nice to use the coloration with contour plots.
set xrange[2:2] set yrange[2:2] set isosamples 50 set pm3d unset surface set view map set contour set key outside splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

You can play with the colour scheme used in the plot. If you are going to print the plot on a monochorme printer, it is useful to use
set palette gray negative
This chooses a gray palette for the colouring. The negative reverses the order, making black represent higher values and white the lower values. There are many more options to the set palette command see help system for details.
set xrange[2:2] set yrange[2:2] set isosamples 50 set pm3d unset surface set view map set contour set key outside set palette gray negative splot exp(0.2*x)*cos(x*y)*sin(y) notitle 

Fitting functions
Gnuplot has the ability to fit a function containing parameters to a data file. Gnuplot contains an implementation of the nonlinear leastsquares (NLLS) MarquardtLevenberg algorithm.
Suppose you wanted to fit a best fit straight line y = mx + c to a set of data points. This can be achieved using the fit command. The fit command takes the a number or parameters
fit expression 'datafile' (optional data modifiers) via param1,param2,....
Let us see this in action, consider a data file data containing 2 columns of data one representing the independent variable time and the other the dependent variable position.
#Time  position 
0.000  2.345 
0.500  2.86 
1.000  3.41 
1.5  3.42 
To fit a best fit (least squares) straight line we use the command on the left. Part of the text output is shown on the right.
fit m*x +c 'data' using 1:2 via m,c  resultant parameter values m = 0.755 c = 2.4425 After 4 iterations the fit converged. final sum of squares of residuals : 0.0802875 rel. change during last iteration : 8.73884e12 degrees of freedom (FIT_NDF) : 2 rms of residuals (FIT_STDFIT) = sqrt(WSSR/ndf) : 0.200359 variance of residuals (reduced chisquare) = WSSR/ndf : 0.0401438 Final set of parameters Asymptotic Standard Error ======================= ========================== m = 0.755 +/ 0.1792 (23.74%) c = 2.4425 +/ 0.1676 (6.863%) correlation matrix of the fit parameters: m c m 1.000 c 0.802 1.000 
From this output we read off the best fit slope m is 0.755 with a standard deviation of 0.1792 and the best fit intercept c is 2.4425 with standard deviation 0.1676
We can put this together with a plot command to plot the data points and the best fit straight line as below
fit m*x +c 'data' using 1:2 via m,c set title "Position versus time" set xlabel "time/s" set ylabel "position/m" plot 'data' title 'data points', m*x+c title 'best fit' 

Error bars in data
In the above cases we have assumed that there is no error in the position measurement (or that the error is identical for each point. In many cases this is not the case and we want to plot the data with errors.
Suppose our data file now contains a third column containing the error in the position
#Time  position  pos error 
0.000  2.345  0.1 
0.500  2.86  0.15 
1.000  3.41  0.4 
1.5  3.42  0.1 
We can fit this with
fit m*x +c 'data' using 1:2:3 via m,c  resultant parameter values m = 0.709309 c = 2.3867 After 3 iterations the fit converged. final sum of squares of residuals : 1.50974 rel. change during last iteration : 8.15835e08 degrees of freedom (FIT_NDF) : 2 rms of residuals (FIT_STDFIT) = sqrt(WSSR/ndf) : 0.868832 variance of residuals (reduced chisquare) = WSSR/ndf : 0.754869 Final set of parameters Asymptotic Standard Error ======================= ========================== m = 0.709309 +/ 0.08091 (11.41%) c = 2.3867 +/ 0.07956 (3.333%) correlation matrix of the fit parameters: m c m 1.000 c 0.724 1.000 
There slope is 0.709309 +/ 0.08091 and the intercept is 2.3867 +/ 0.07956. In this case the error is smaller since the wayward point (3rd line in data) had a much higher error. Note that it is important to include the using 1:2:3 otherwise it will by default only use the first two columns!
This can be plotted together with the data points as
fit m*x +c 'data' using 1:2:3 via m,c set title "Position versus time" set xlabel "time/s" set ylabel "position/m" plot 'data' u 1:2:3 title 'data points' with errorbars, m*x+c title 'best fit' 
