Introduction to GnuPlot

College of Natural Sciences Computing Laboratories
http://www.cs.uni.edu/Help/gnuplot/ University of Northern Iowa
Cedar Falls, IA 50614


Gnuplot is a command-line driven program for producing 2D and 3D plots. Although it doesn't have as many features as some of the commerical mathematical software available, it isn't as complex to use as packages such as Mathematica or Matlab. It is ideal for a users you only need a plot of a graph, and who don't want to learn a major tool.

The features and topics on Gnuplot covered in this document include :

If you have questions at any time, you can access the on-line help by typing help within Gnuplot. Gnuplot has a very good help system.

Starting and Quitting Gnuplot

To access Gnuplot, you probably want to be logged into one of the Suns in Wright 339. It is possible to run GnuPlot on any Xserver, but that is beyond the scope of this document. When you are logged into a Sun, you can do one of the following: To quit gnuplot, type exit, or hit Control-D.


Specifying Functions in Gnuplot

In 2D plots, the variable to use is x, in 3D plots, use x and y.

Multiplication is denoted by *, and division by /. Exponents are denoted by**, and all multiplication must be explicit. That is, 3x would generate and error, you would want to use 3*x.

For example, the polynomial 3x4 + 4x - 2/3 would be the following in Gnuplot:

Gnuplot also has a number of predefined functions. These are called by putting the arguments in parenthesis, i.e., sin(x). These include the following: The following are other examples of functions. Make sure you understand what functions are being described.

A Simple Example

For a quick example, let's say you wanted a graph of sin(x). You would then type the following at the gnuplot> prompt: This will pull up another window with the graph you wanted. If you made a mistake or want to slightly change what you typed, hit the UP ARROW. This will pull up what you typed. If you have typed a couple of lines, you can keep hitting the arrow button. The you can use the left and right arrow keys to change what you typed. As a quick example, try changing what you typed to

Graphing Two Dimensional Functions

The command used for two-dimensional plots is plot. The simplest use of it is: For example, to plot x3, type You should see something like the following pop up in the graphics screen.

For another example, to see what the hyperbolic cosine function looks like, type

This should display

Note that in this picture the scale isn't the best for finding a lot of information about the graph. It tells us that the function gets very large as x gets larger. But if we want to see what the function looks like closer to 0, we need to change the scale. Gnuplot uses an autoscale mechanicism. It sets the scale so that the graph will fit on the screen. To change the scale, use one of the following forms of plot:

Note, that if you set the range for the x values on one plot, they will stay that way for future plots. To set the default x range back to [-10,10], type the following: Also, if you set the range for the y values, they will stay the same for future plots as well. You can set GnuPlot back to autoscaling the y axis by typing the following: For more information on the set xrange and set autoscale commands, use the help command. To see what cosh looks like from x=[-5, 5], type Or, to see what cosh looks like from y=[0, 10], type

Graphing Three Dimensional Functions

The command used for three-dimensional plots is splot. The simplest use of it is: For example, to plot the function z = -x3 -y, you would type the following: You should see something like the following:

You can change the scale in a similar manner to plot:

Or, you can use the following commands to change the default ranges for subsequent graphs: To change back to the default x and y ranges, type the following: It is important to note that if you set the range for the zaxis in one plot, it will remain at that range for subsequent plots. If you want to turn GnuPlot's autoscaling back on, type: For more information on autoscaling, type help autoscale. Also, if you get an error about an invalid range, you need to change the ranges you are using.
Hidden 3D view

Hidden 3D view

Sometimes, 3D graphs can be hard to interpret. For instance, the graph of could be seen by typing the following:

Note that in this graph, the set grid command was used. To make viewing this easier, you can use the set hidden3d command. For instance, if you typed the following, you would get:


Increasing Precision of 3D plots

When you look at the previous graph, it seems that the resolution of the graph is not very high. To decrease the amount of choppiness in the graph, you need to increase the precision used. This can be done for 2D plots by the set samples command, and for 3D plots by set isosamples command. You will almost always have to use this for 3D plots, because the default sampling rate is very low. The syntax of the command is: The default is for both rates to be set to 10. For example, typing the following yields:

It is important to note that the higher you set the isosamples, the longer it will take to create the graph. In most cases, you won't want to set the sample size larger thant 100.


Adding Contour Lines

The following commands relate to contour lines in 3D plots: Note that the set contour surface option is not available with the set hidden3d option. Typing the following commands yields the following two graphs:

If only the contours lines are desired, the set nosurface command will turn off drawing the surface. For more information on this, type help set surface. The drawing of contour lines is highly custimizable, for information type help set cntrparam.

For example, if you only want the contour lines for z=.2, .4, .6, you could enter the following:


Changing View of Graph

Many times, you will want to change the view of a graph. To do this, you need to use the set view command. This command is fairly unwieldy. The syntax for the command is one of the following: The first argument is the angle between the viewpoint and the horizontal axis of the screen. The second is the angle between the axis perpendicular to the screen. The third number if the zoom factor. The default values are 60, 30, 1. To change back to the default view, type:

For instance, to see how changing the horizontal angle changes the graph,consider the following:

To see what happens when you change the vertical angle, consider the following:

To see an example of zooming, consider


Parametric Equations

GnuPlot includes support for Parametric Equations. To switch to parametric mode, type the following: To go back to standard Cartesian mode, type: For example, to see the plot of the set of equations x = 5 cos t and y = 2 sin t, you could type the following:

The xrange and yrange values specify the range of the graph displayed. The set trange command sets the range that is used to compute the parametric equations. If you use brackets to set a range within the plot command, it will refer to the trange. The first part of the plot command before the comma is the x equation, and the second part is the y equation.
For another example, consider trying to plot the cycloid x = t - sin t and y = 1 - cos t.

3D Parametric Plots

Gnuplot also supports 3D parametric plots. It uses the the variables u and v. 3D paramettric plots use the xrange, yrange, and zrange values to determine what is displayed on the screen. The urange and vrange variables can be changed to determine how much of the graph is drawn. For example,:

If you changed the urange and vrange parameters, you would get a differant graph.

Many of the standard 3D features apply to 3D parameter plots (you can use isosamples, views, and hidden3d).


Polar Plots

To switch to graphing with polar coordinates, type: To switch back to Cartesian coordinates, type: In polar mode, the independent variable x corresponds to the angle, or theta noramally used for polar plots. Polar plots are always plotted in a rectangular box, to change the size of the graph, use the set yrange command. This will change both the horizontal and vertical range. For an example, consider the following:

To change the displayed range so their is extra space around the graph, type:

Note that this would leave the yrange set to [-4:4] for subsequent plots. To turn autoscaling back on, use the following:

The default for interpretation of the angle is radians. To switch this value, you can use one of the following:

3D Polar coordiantes

GnuPlot supports the 3D equivalent of polar coordinates, spherical and cylindrical coordinates, are only available for 3D data plots. For information on them, see help set mapping.

Plotting Data

One of the most powerful features in GnuPlot is how easily Data can be plotted. For example, we have the following data file (in /opt/Gnu/info/gp/example1.dat). The data was generated by applying euler's method to a ODE problem. The first column is the number of subintervals. The second column is the step size (1/(# of subintervals)). The third column is the value obtained, and the fourth column is the absolute error.
# Example1.dat
# number of subint.   - width of subinterval, computed value, abs. error
0 1			5		 0.00673794699908559
1 0.5			5.0009765625	 0.00576138449908559
2 0.25			5.00317121193893 0.00356673506015159
3 0.125			5.00478985229103 0.00194809470805701
4 0.0625		5.00572403277733 0.0010139142217529
5 0.03125		5.00622120456923 0.000516742429855555
6 0.015625		5.00647715291715 0.000260794081935245
7 0.0078125		5.00660694721608 0.000130999783004349
8 0.00390625		5.00667229679632 6.56502027673866e-05
9 0.001953125		5.0067050843668  3.28626322820824e-05
10 0.0009765625		5.0067215063061  1.64406929883398e-05
11 0.00048828125	5.00672972430911 8.22268997247022e-06
12 0.000244140625	5.00673383506831 4.11193077187733e-06
13 0.0001220703125	5.00673589088727 2.05611181058885e-06
14 6.103515625e-05	5.00673691890656 1.02809252577885e-06
15 3.0517578125e-05	5.00673743294363 5.14055459532869e-07
16 1.52587890625e-05	5.00673768996904 2.57030048800289e-07
17 7.62939453125e-06    5.00673781848355 1.28515534214557e-07
18 3.814697265625e-06   5.00673788274127 6.42578132925564e-08
19 1.9073486328125e-06  5.00673791487013 3.21289537197345e-08
20 9.5367431640625e-07  5.00673793093482 1.60642699142954e-08
21 4.76837158203125e-07 5.00673793896686 8.03222910406021e-09
Note that lines beginning with a # are considered comment lines and are ignored. To plot this data, you can type the following: (if the file isn't in the first level of your home directory, you can specify the full path, or see the directions on Saving and Loading From a file for information on changing directories.)

This plots points (x, y) where x is from the first column and y is from the second column. To make the graph a little easier to read, you could type the following:(for information on these, see logscale, Line Style)

Changing which columns are plotted

GnuPlot also lets you plot data from differant columns against each other. You add the using keywork to a plot command. For example, to plot the computed value (column 3) against the number of subintervals (column 1), you could type:

Or to plot the third column against the 4th column,

There are many advanced options for plotting columns against each other like this, for more information see help plot datafile using.

3D Data Plots

GnuPlot also lets you do 3D plots. The Data File must have three columns, one for the x, the y, and the z values. For instance, if you had a data file like the following:
-2.000000	-2.000000	0.500000
-2.000000	-1.500000	0.427300
-2.000000	-1.000000	0.235294
-2.000000	-0.500000	0.062257
-2.000000	 0.000000	0.000000
-2.000000	 0.500000	0.062257
-2.000000	 1.000000	0.235294
-2.000000	 1.500000	0.427300
-2.000000	 2.000000	0.500000
-1.500000	-2.000000	0.427300
-1.500000	-1.500000	0.500000
-1.500000	-1.000000	0.371134
-1.500000	-0.500000	0.109756
-1.500000	 0.000000	0.000000
-1.500000	 0.500000	0.109756
-1.500000	 1.000000	0.371134
-1.500000	 1.500000	0.500000
-1.500000	 2.000000	0.427300
-1.000000	-2.000000	0.235294
-1.000000	-1.500000	0.371134
-1.000000	-1.000000	0.500000
-1.000000	-0.500000	0.235294
...
To plot this data, if it were in a file called "try2.dat", you would type:

You can also use cylindrical and spherical coordiantes with 3D data plots. For example:

For more information, see help plot datafile.


Generating Output

The next couple of pages deal with getting output from the graphs you have created. There are several ways you can do this:

Printing to Printer

Once you have the plot you want on the screen, do the following to print the graphic to a printer: After the last command, you should see a message like the following: This means that is was printed.

To go back to having the graphical display, type the following:

If you want to print later, you only have to do the last three of the commands, i.e., Note that the lp in the output command is the print command for your machine. Use can use the following for the output command:

Outputting to a Postscript File

There are two main uses for graphs in Postscript format. The first is to have a copy you can print later, without using GnuPlot. You need regular Postscript files for this. The second is to include the graph in another document. For this option you need to use Encapsulated Postscript Files. This is a special form of Postscript that can be included in documents. (EPS files don't have the extra lines that are used when a PS file is printed directly to a printer). To generate a postscript file, do the following: To print this file from the command line (not in GnuPlot), type If you print to this file again, it will append the graph to the end of the file as a second page. For instance, would create a 2-page postscript file called "file2.ps". The first page would be the plot of z=sin(xy) and the second page would be the plot of y=x2. Usually, you will only want the one graph in each PS file.

When you want to return to printing to the screen, type the following two lines:

Options for set terminal postscript

There are several options for this command:

Printing to EPS files

To print to an EPS file, you do the same as for PS files, but use the following set terminal command. Make sure you only print one image to each EPS file.

Outputing to Graphics files

You cannot output directly from GnuPlot to Graphics files. You could use the convert command (convert test.ps test.gif) if you had printed to a file, or you can use the screen grab option in Image Magick. Do the following to get a graphics files version of a graph.
  1. Have the graph you want displayed in a graphics window.
  2. Have ImageMagick started. You can do this by typing display & in a shelltool or commandtool (not at the gnuplot prompt).
  3. If you didn't have Gnuplot already running, choose Load from the menues that pop up when you hold a mouse button down over Image Magick's screen.
  4. Choose Grab
  5. Move the Grab window if you have to, and make sure that the window with your graph in it is unobstructed.
  6. Click Okay in the Grab Window. Then click the left mouse button in the window with the Graph you want.
  7. After a couple of seconds, a copy of the graph should pop up in GnuPlots' window. You can resize it or apply effects to it within ImageMagick.
  8. Choose Save from ImageMagick's menu.
  9. Choose format from the Save screen.
  10. Select the graphics type you want (i.e., .gif or .jpeg.
  11. Give the file the name you want, and click on Save.
For more information on ImageMagick, see here for information on the display program or here for information on the convert program.

Saving and Loading from a File

Gnuplot lets you load a series or commands in from a file. This is useful when you are trying to "tweak" a lengthy expression to get the output that you want. If you haven't used an UNIX editor before, you will probably want to start with PICO. You can start it within a terminal window by typing pico, or you can select it from the Editors menu of the Wright Hall Menu. For information on how to use Pico, see here. For instance, you might need to enter the following lines to get a graph that you want. You could put this in your home directory in a file called, for instance, "work.gnu". Then to run these commands, you would type the following in GnuPlot: Or if the file is in a differant directory, This file is on the system, if you want to try it, type The line beginning with the "#" is a comment line. You can put these in your text files as comments to yourself.

Changing Directories

If you want to put the file in another directory than your home directory, you just need to use the cd command in GnuPlot. First, to see what directory you are in, type the following: You should see something like "/user/bos", where your username is in place of "bos". To change directories, just use the cd command as follows:

Adding Pauses, Looping Animations

To make changing GnuPlot graphics, you can specify multiple plots, and just put pause statements between them. For more information, see help pause. For an example, type load '/opt/Gnu/info/gp/work2.gnu'. Also, if you put a reread statement into your text file, it causes GnuPlot to go the beginning of the file, and keep looping. For more information, see help reread, and for an example, type load '/opt/Gnu/info/gp/work3.gnu'. To exit the loop, hit Control-C in the GnuPlot window.

Saving Work

The option that GnuPlot gives for saving work is the save command. If you type the following: GnuPlot will then create a text file with the name you gave it that includes set commands for every possible setting in GnuPlot. You can then load this file to continue work where you left off.

Using a Log Scale on the axis

Sometimes, when a plot has drastic changes in one of its variables, it is useful to use a log scale on that axis. For instance, the graph of cosh(x) for x=[-10,10] looked like:

If we wanted to use a logscale on the y axis, we would use the set logscale command. The usage of this command is

To see what logscale is being used, type: To turn logscaling off for a axis, use We if typed the following lines in, We would get the following graph.

This can also be useful for data plots.


Displaying a Grid behind Graph

You can display a grid with the graph by using the set grid command. To see if grids are being used, type show grid. For example, if you typed the following, You would get the following:

Grids can be turned on for 3d plots as well. They often improve the 3D perspective.

To turn the grid feature off, type set nogrid.


Overlaying Multiple Plots

To overlay multiple plots, you can just list them in the same plot command, putting comma's between them. For example: produces the following:

You can add more complex arguments, or mix functions and data:

You can overlay as many graphs as you want. In addition to listing all of the commands on the same line, you can use the replot command to add functions. For instance, the first example above could have been like this: You can overlay multiple graphs of any kind, 3D, parametric, etc...

Changing Styles of Lines

You can set the style of plotting for both function and data plots. To change the default style for functions, use the set function style command, and to set the default for data plots, use the set data style command. To see the current line style, type the following: You can also add the with keywork to plot and splot commands. For example, You can also specify differant line style when overlaying differant plots, for instance, This produces the following graph:

Different Line Styles

The following line styles are available for 2D function and data plots: `lines`, `points`, `linespoints`, `impulses`, `dots`, `steps`, `errorbars`, `boxes`, and `boxerrorbars`

Lines

This is the default plotting style. It connects the data points with a line. Note that if you are doing a Data plot, blanks lines in the data file will cause gnuplot to not connect the data points with a line.

Points

The Points Style puts a point at each data point.

LinesPoints

This is a combiniation of the two style - Lines and Points.

Impulses

The impulses style draws lines from the x-axis to each point.

Dots

The Dots style places very small dots for each data point. This would be useful for scatterplots with large amounts of data.

Steps

This connects consecutive points with two perpindicular line segments.

Error Bars

GnuPlot can add error bars, which suggest a range of data, only for 2D data plots. They use the third columnd in the file as the "delta" value. For more information, see help plot errorbars.

There is also a BoxErrorBars style that combines this style with boxes.

Boxes

This draws boxes from the xaxis to the the points.

3D Plots

The only line styles available for 3D plots are "lines", "linespoints", "impulses", and "dots".

For more information on line styles, see help set style

Evaluating Expressions

You can use the print command to evaluate any expression for a numeric answer. Here are some examples:

Defining your own variables

GnuPlot allows you to define your own constants and functions. To define a constant, just use For example, This could be useful for changing a constant in an expression, for example, The replot command would change the graph to reflect the new constant. Note that you cannot overlay graphs of the same function using differant values for a constant. The replot command reevaluates the function, so it will always use the current value of a variable. For instance, the preceding example would just plot the graph of sin(4*x). If you wanted to overlay graphs with two differant constants, you would need to use two differant constants, i.e., . This would produce the following graph

You could then change any of the constants and just replot to see the effects of changing the constant.

Defining your own functions

The syntax for defining your own functions is as follows: Here are some simple examples: You can use these functions like any other functions in GnuPlot,

Using Condition Statements in Function Definitions

It is possible to define piece-wise function is GnuPlot. Gnuplot uses the if statement syntax of C. For instance, you could define your own absolute value function by the following: Gnuplot first evaluates the expression in the parenthesis. If it is true, it then performs the expressions after the "?" mark. If the expression in the parenthesis is false, it evalues the expression after the ":". You can also define more complex piece-wise functions by nesting the if statements. For example, produces the following graph:

For more examples, see help user-defined


Changing Variables

Sometime, you would rather use other variables names than x and y for your plots. GnuPlot allows you to change the name of the independent variable. You do this using the set dummy command. For instance, if you were working with 2D plots with t as the independent variable, You can change the dummy variables for 3D plots as well, with one of the following: For more information, see help set dummy.

Changing Axis Labels

If you want to add Labels to your axis, to describe them, you can use the commands : Note that the ylabel string in 2D plots will appear at the top left corner of the screen, using a Graphic view. However, it will be vertically placed in a postscript plot. If you want to move the label, you can use the following offsets after the ylabel graph: These will add labels of the string you specify to the graph. For instance, typing the following: will produce the graph

Labels work the same in 3D plots, where the zlabel is used as well. To turn off the labels, Just use the set xlabel with no arguements.

Displaying Zero Axises...

You can turn off the dashed lines that represent the x=0 and y=0 lines in 2D plots. To turn them off, use one of the following: For example, if you typed the following: You would get :

Turning off Border and Graph Key

Command relating to border - You can also turn off the display of the function names in the upper right hand corner. Related commands - For example: produces the following:

Changing "Tic" Marks on the Borders...

You can turn off the markings on the axis by using one of the commands like set noxtics. For instance, typing the following: produces the following graph:

To turn the tics back on, use set xtics or set ytics. You can also make the Tics marks correspond to Days of the week (i.e., set xdtics, or months (i.e., set xmtics). For instance, typing the following:

Produces the following:

Ticslevel

One final thing, with splots, you may have noticed that the graph is always raised above the base. If you want to lower it, see help set ticslevel.

Adding Title and Time

To add a title to your graph, use the set title "Title String" command. For instance: To turn the title off, just use set title with no arguments. You can also display the time in the lower left hand corner by using the set time command. To turn off this, use set notime. Typing the following: produces the following:

Other Commands

There are other commands that may be useful in changing the appearence of the graph. Use the help command to get more information.

GnuPlot for Windows

GnuPlot is also available for Windows. To access it in the PC lab in Wright 112, do the following: Most things should work the same in Windows as they do on Unix. To print output to a printer, Just click on the Print button. It will first come up with a window asking which terminal to use, type in "postscript". It will then come up with a window asking which Port to use, use LPT1:. This will print to the Laser Printer in Wright 339.

If your screen goes to blue, and you get an error message about Dynamic Commands or something, just hit y to return to Windows. For some reason, when GnuPlot tries to plot certain functions (such as 3D plots involving exp, it causes an error.


Downloading and Installing on a PC with Windows 3.1x

If you want to install GnuPlot on your PC, the software is available for free. You can either download it through the Web, or copy it onto a floppy in the Wright Hall labs.


Web Download

To download a copy of GnuPlot click here.

Your browser will ask if you want to save the file, if you have a temp directory on your drive you might want to save it to that directory. After you have selected the directory you want to use, click OK and the file will be saved to that directory.


Copying Source file to Floppy

Bring a floppy into the lab in Wright 112. After logging in, type the following:

Installing GnuPlot in Windows

To install GnuPlot in Windows you first need to run the file you downloaded. In the Program Manager choose File, then run, then type the name of file you downloaded or copied to a floppy. You should then see the Gnuplot installation program. (If you did not you might have a bad copy and you should download it again.) Press return on the install directory screen. Gnuplot will then be installed on your hard drive.

To add the Gnuplot icon, select File in Program Manager, and select New. Select New Group and click OK. Type Gnuplot in the description line and click OK. Open the folder you created. Again select File from the Program Manager menu, select New, select Program Item and click OK. Select browse to find the Gnuplot directory on your hard drive. In that directory, select wgnuplot.exe, and then OK. Click OK on the Program item Properties box and you should then see the icon for gnuplot. Double click on the icon to start the program.