Gnuplot
From AIMSWiki
Gnuplot allows you to produce graphs and surface plots of functions and given data.
To start Gnuplot type gnuplot inside an xterm. You will get something on the screen that looks like:
When in doubt, read the Gnuplot help by typing
help command
at the Gnuplot prompt gnuplot> .
command is the name of the Gnuplot command or function on which to find help.
To quit Gnuplot, type quit. A shorter way to quit is just to type q.
| Table of contents |
Examples
Gnuplot v.4.0 Examples gallery (http://gnuplot.sourceforge.net/demo_4.0/)
Changing Aspects of Your Graph
set is a very important command. If you type help set you will see how many different options it has. Here are a few of the things that can be done using set:
- Add a title to your graph
- Label your axes
- Generate a postscript file of your graph for printing or putting in a LaTeX document
- Set the minimum and maximum x and y values for your axes (called the x and y ranges respectively)
- Set the size of a graph
- For a surface plot (splot) you can set the viewing angle
- Using multiplot, several graphs can be put on one page or terminal window
- Draw a contour plot
Adding a title
To add a title to your graph, simply type set title "My graph" where My graph is whatever you want the title to be.
Labelling the axes
Axes can be easily labelled in Gnuplot. For instance, to label the x-axis "time" use set xlabel 'time' and similarly for the other axes.
Note that if you want to put a label inside a graph at a particular point, this can be done using set label 'name', where name is the label you want to use.]
For example:
set xlabel 'time' set ylabel 'distance' set label 1 'Highest point of trajectory' at -2,20 plot 10*x-5*x**2
(The 1 is a tag that allows you to change/remove this label later on, for instance using unset label 1).
Changing the range of the axes
You will often find that you want to change the range over which a function is plotted. To do this, you can use the commands set xrange and set yrange. For example if you plot the function y=tan(x), you will find that it looks bad. In fact it's wrong - GNUplot does not plot this function well by default. If you set the ranges as follows
set xrange [-5:5] set yrange [-10:10] plot tan(x)
you'll get a much nicer graph. Compare the graph on the left (with default settings) with the one on the right (where the x and y ranges have been changed).
Plotting a vector field
import and initialise gnuplot creat arrays data=[x,y,u,v]
- plot(data)
The replot command
Very often you have plotted a graph, and will want to redraw it with some minor change (for instance with a title, or from a different viewpoint). Rather than enter in the whole command again, you can just type replot.
Replot can also be used if you want to display more than one graph on the same set of axes. This will be explained in the next section.
Plotting several functions on the same graph
As well as replotting a graph, the command replot can also be used to plot several functions on the same axes. For example try the following:
plot sin(x) replot cos(x)
Increasing number of plotted points
Sometimes if the functions you plot are not smooth enough or well rounded, it may only be because you need more points to be plotted. To increase manually the number of plotted points to N, use
set samples N
Surface plotting
Splot allows plots of surfaces. A surface is specified mathematically by a function z=f(x,y).
The basic syntax is very similar to the plot command. For example splot sin(x)*y**2 produces the following graph:
To change the view of the graph, you can just click and drag the graph. Note however that there may be problems if you try to save the rotated graph as an eps file (LINK THIS TO PRINT PAGE). In this case use the set viewLINK HERE command to set the viewing angle.
One useful option is to draw contours of your graph. This is simple to achieve. For instance,
set contour splot 0.003*x**4-0.002*y**4<p>gives the following output:
More usefully, the contours alone may be plotted by changing the view, and removing the surface:
set contour unset surface set view 0,0 (This shows just the x-y plane) set cntrparam levels 20 (This changes the number of contours drawn) splot x**4+2*y**4
Changing the viewing angle of a surface plot
The set view command is used with the splot command to change the viewing angle. The command is as follows:
set view <rot_x>, <rot_z>, <scale>, <scale_z>.
<rot_x> must lie between 0 and 180 degrees, while <rot_z> lies between 0 and 360 degrees. <scale> determines the overall scale, while <scale_z> is just the scale of the z-axis.
The default view is 60,30,1,1.
For a contour map use set view 0,0. This shows just the x-y plane.
Functions
Built-in functions
-
exp(x): ex -
log(x): logex -
log10(x): log10x -
sqrt(x):
-
x**y: xy. Note that rather than using fractions you should use decimals for y. -
abs(x): | x | -
sgn(x): 1 if x > 0, − 1 if x < 0 and 0 if x = 0. -
sin(x): sine (in radians)</span> -
cos(x): cosine (in radians)</span> -
tan(x): tangent (in radians)</span> -
acos(x): cos − 1(x) -
asin(x): sin − 1(x) -
atan(x): tan − 1(x) -
sinh(x): hyperbolic sine -
cosh(x): hyperbolic cosine -
tanh(x): hyperbolic tangent -
asinh(x): inverse hyperbolic sine. The other inverse hyperbolic functions are obtained similarly. -
norm(x): normal (Gaussian) distribution function -
invnorm(x): inverse normal (Gaussian) distribution function -
erf(x): error function, erf(x) =
.
-
inverf(x): inverse error function of x
Defining your own functions
You can define your own functions of up to 5 variables and plot or use these in Gnuplot. Functions are defined using
<function_name>(<var1>, <var2>, ..., <var5>) = <expression>
For example,
f(x) = x**2 + 2*x + 2
User-defined functions can be use in plots. From the previous example, plot f(x) will draw the defined parabola. This can be especially useful when plotting piecewise defined functions. We plot the function
f(x) = (x < 0) ? 1: x**2+1 plot [-5:5] f(x)
Note the syntax used in defining the function. The (...) ? ... : ... syntax evaluates the expression between the brackets, and returns the value after the ? if it is true and the value after the : if it is false.
Printing and including graphs in LaTeX
To print a graph, do the following:
set terminal postscript set output "| lpr" replot set output set terminal x11
If you want to include a graph in a LaTeX document, for instance an essay or an article for a journal, you should save the graph as a pdf document. To do this, type:
set terminal postscript eps enhanced set output "myfile.eps" replot set output set terminal x11
myfile should be replaced by whatever you choose as your filename.
You should notice the common elements of the two. In both cases you set the terminal type to something, and then set the output to where you want it to go. Having replotted the graph, you can finally return the terminal to its original setting, which is x11.
These commands have changed from previous versions of GNUplot. Now you must use the extra set output command to stop the output being sent to (and overwriting) the file you created.
We use set terminal postscript eps rather than set terminal postscript because the eps format means that the graph is the right size and orientation to put in a LaTeX document. However, you may prefer to keep it as a normal postscript - this is up to you!
When you set the output, you can set up other options - for example set terminal postscript eps color will produce a file that is in color. Try typing
? set terminal postscript to see a full list of the options.
For lazy typists, the shorter versions of the commands are: set term post eps, set out "file.ps", etc. You can work out which shortcut does what.
Other things Gnuplot can do
- Parametric plots
- Plotting using polar coordinates
- Logarithmic plots
- Define custom line styles
- Adding a grid to graphs
- Plotting from data in a file
- Animations
- Plotting histograms
- Creating several different windows for plotting using multiplot
Plotting ellipsoids and hyperboloids - parametric equations
To plot a closed surface, such as an ellipsoid, you should use the parametric mode. What this means is that you will plot a surface in terms of the dependent variables u and v. These coordinates can be thought of as the spherical polar angles θ and φ.
So to plot the ellipsoid
you should type the commands
set parametric set xrange [-3:3] (Note: these commands are just to make the set yrange [-3:3] plot look better. They set all the axes to set zrange [-3:3] be the same size.) splot cos(u)*cos(v),2*sin(u)*cos(v),3*sin(v)
Why this? Well, the splot command in parametric mode plots the surface (cos(u)cos(v),2sin(u)cos(v),3sin(u)). The x,y and z-ranges were included just to make the axes the same sizes.
To leave parametric mode, type unset parametric. Then gnuplot will work as normal.
To plot the hyperboloid
you should type the commands:
set parametric set xrange [-6:6] (Note: these commands are just to make the set yrange [-6:6] plot look better. They set all the axes to set zrange [-6:6] be the same size.) splot cos(u)*cosh(v),2*sin(u)*cosh(v),3*sinh(v)
Note that we had to do a bit of math ourselves to get the equations in parametric form! You can use unset parametric to leave parametric form.
Contour plotting
You may have met the idea of a contour plot when you look at a map. On it you may see many closed loops, lines where the height is the same. On the diagram below there are three contours, representing places where the height is 1000m, 1100m and 1200m. The local maximum height (the top of the mountain) lies inside the smallest contour curve.
To plot the contours of x4(1 − y2) + 2y4 you could do the following:
set contour splot x**4*(1-y**2)+2*y**4
This gives you the surface, together with a contour plot below it. You probably want to increase the number of contours shown. To do this, type set cntrparam levels 20, although if you want even more contours, just increase 20 to whatever you want. Remember to type replot to show the updated graph.
You may also just want to see the contour plot, without the surface. To do this type
unset surface set view 0,0 replot
The set view command means that you see the contour plot properly (in other words you just see the x-y plane). If you are a perfectionist, you may want to get rid of the annoying stuff to the right of your plot. To do this, type unset key, followed by replot.
Finally, if you want to undo anything, just type unset cmd where cmd was the command that was chosen using set before (or set if the command was previously unset).
Choosing line and point styles in terminal, plot data files and enable grid
In order to see the different line and point styles a specific terminal has to offer you can run the test command. Lets use the postscript terminal as an example:
set term postscript eps # on my system this is the best terminal, it produces almost perfect plots set output "test.eps" test set output set terminal x11 pwd
The command pwd will display your current working directory. In this directory there should now be a file called test.eps. Open this file with a postscript document viewer (ggv will do the job). On the right hand side you will see the available line and point styles supported by the postscript terminal. You can use the set line style command (gnuplot version 4.0) to define your own line and point style combinations. I found the following combinations useful:
set style line 1 lt 1 lw 1 pt 1 ps 3 set style line 2 lt 2 lw 1 pt 4 ps 3 set style line 3 lt 4 lw 1 pt 6 ps 3 set style line 4 lt 1 lw 1 pt 8 ps 3 set style line 5 lt 7 lw 1 pt 12 ps 3 set style line 6 lt 6 lw 1 pt 3 ps 3
The number after line is the index of you custom point/line combo. Option lt choose the line type, lw set the width, pt set the point type and ps set the point size.
Suppose you now want to plot two sets of data on the same graph with different line and point types. The first set of data is in column 1 and 2 of file1.dat and the second set in column 1 and 2 of file2.dat. We will use line/point index 4 for the first set of data and line/point index 6 for the second set of data. If you do not have data files available just use the following data:
#file1.dat #file2.dat #x y #x y 1 1 1 4 2 4 2 8 3 6 3 12 4 8 4 16 5 10 5 20 6 12 6 24 7 14 7 28
Now we can plot the data with a grid enabled. I assume file1.dat and file2.dat to be in your working directory.
reset # just to make sure that nothing will interfere we return to the default
# settings.
# always start your plot with this to avoid unsetting everything at the
# end of the plot
set term postscript eps enhanced # choose postscript terminal
set output "myplot.eps" # output will be written to this file which we can view with ggv
set key below # enable the legend and place it below the plot
# we define our line/point combinations
set style line 1 lt 1 lw 1 pt 1 ps 3
set style line 2 lt 2 lw 1 pt 4 ps 3
set style line 3 lt 4 lw 1 pt 6 ps 3
set style line 4 lt 10 lw 1 pt 8 ps 3 # we will use this combo
set style line 5 lt 7 lw 1 pt 12 ps 3
set style line 6 lt 6 lw 1 pt 3 ps 3 # and this one
set mxtics 2 # I want two minor tic marks on the x axis
set mytics 5 # and 5 on the y axis
set grid xtics ytics mxtics mytics # enable the grid with major and minor tic marks
set title "My plot example" # define a title
set xlabel "x axis label"
set ylabel "y axis label"
set xrange [0:8] # choose the x data range on the plot
set yrange [0:30]
# plot the data in column 1 and 2 of file1.dat and file2.dat with our own line styles (4 and 6 )
# specified by the ls option
plot "file1.dat" using 1:2 with linespoints t "legend label 1" ls 4,\
"file2.dat" using 1:2 with linespoints t "legend label 2" ls 6;
set output
set terminal x11
You can copy and paste this directly into gnuplot OR copy and paste it into a script file. Suppose the file is called example.sh. You can then run the code in gnuplot by typing:
load "example.sh"
Remember the output will be in a file called myplot.eps (in your working directory) which can be viewed with a postscript document viewer such as ggv. Aminating Objests







