Computational Physics 2007

Brief guide to Gnuplot

It is recommended that you write the results of your program to a file, then plot those results separately. This means you can play with the presentation of your results without having to re-run your program.

Gnuplot is a free plotting program that can plot datafiles and user-defined functions. It can't do everything you might possibly want, but it is very easy to use. This is a simple on-line guide to getting started with gnuplot.

Format for data

Gnuplot expects data to be arranged in columns in an ordinary text file, for example:

# Gnu population in Antarctica since 1965
         1965   103
         1970   55
         1975   34
         1980   24
         1985   10
You can have as many columns as you like. Comments are indicated by "#".

How to use gnuplot

To run gnuplot interactively, type:

You can also run gnuplot directly within UNIX, taking input from a file, e.g.
gnuplot < file.gnu
where file.gnu contains a list of gnuplot commands. This latter option is one you may wish to use once you know how to use gnuplot.


You can get help by typing "?" or "help". The on-line help is very good.

You can abbreviate commands to save typing.

An example plot command

First, let's define a function:

  pop(x) = 103*exp((1965-x)/10)
Then we can plot this function, for x from 1960 to 1990, thus:
  plot [1960:1990] pop(x) 

To plot the datafile given above (assuming it is called population.dat),

  plot 'population.dat'

And to plot both the function and the data,

  plot [1960:1990] 'population.dat', pop(x)

By default, data files are plotted point by point. If you want lines joining the points,

  plot 'population.dat' with linesp
If you want lines only,
  plot 'population.dat' w lines
To control which colour each set of lines and points comes out, see help plot. For example, to make the data come out with color 2 (dotted lines), and pop(x) with colour 1,
  plot [1960:1990] 'population.dat' w lines 2 2, pop(x) w lines 1 1
To plot column 4 of "flib.dat" against column 2 of the same file,
  plot "flib.dat" u 2:4 w linesp
(This gives column 2 on the x axis and 4 on the y axis.) You can also plot points with errorbars. This command plots column 4 versus column 2, with columns 5 and 6 defining the upper and lower error bars:
  plot "flib.dat" u 2:4:5:6 w errorbars

Printing graphs into PostScript files

The following sequence changes the terminal type to PostScript and replots the most recent plot to a file called

  set term post
  set output ""
Don't forget to set the terminal type back to X11 when you have finished plotting to the file:
  set term X

In order to get graphs that are readable when included in papers, I recommend

  set size 0.6,0.6
before plotting to the file. This reduces the size of the graph while keeping the font size and point size constant.