GNUPlot Tutorial
Introduction
The best way to learn GNUplot is by plotting simple functions and learning how to plot them nicely. All the features that you learn for functions also apply to data files. With this tutorial we will try to show you the basics of plotting with GNUplot and we will show you some more advanced commands with examples. At the end of the tutorial you should be able to produce high quality plots.
To see how powerful GNUplot can be check the following links:
The frames of the following movies were generated using GNUplot (25fps)
http://dbalague.blogspot.com/2013/05/bclr2.html (check the tables near the end of the page)
The figures in the following papers were also generated using GNUplot:
http://arxiv.org/pdf/1210.6795v1.pdf (Pages 3, 21, 22, 23)
http://arxiv.org/pdf/1109.5258v1.pdf (Pages 34, 35, 36)
Before we start, and to improve the speed of the rendering and avoid possible crashes with big data files, we recommend using the X11 term:Â
set term x11
Some of the fonts or symbols may not display as desired (as the X11 terminal is quite simple), but they would in a different format as we explain below.
Simple Functions
We will start with a very simple example. A lot of places use this as the first example, and we will use it too.Â
plot sin(x)
This will plot the function sine as shown below:
We can plot any function that you can imagine. For example, let's plot this function
with the following command:
plot x/2*exp(x)
We can try with the absolute value,
We can plot this function using the following code:
plot abs(x)
or we can use the ternary operator " ? : " :
plot x>=0 ? x : -x
They both produce the same plot:
Simple Plotting: Range, Grid and Size
Range
We can improve the look of our plot by changing the range of our axes. For instance, for plotting the function , we might not want to see the behavior when the values are small (negative) as we know that the values of the function tend to zero. We can set the range for x with the command set xrange [begin:end]:
set xrange [0:5]
plot x/2*exp(x)
Observe the result:
We can see that the y-axis has been adjusted according to the values of x. Gnuplot is quite good at this. One can also cut the range of the y-axis in a similar way: just use yrange instead of xrange. If we are plotting a 3D figure, then we can also adjust the range of z in a similar way.
Grid and Size
In some cases we may need a grid. We can add it like this:
set grid
replot
To unset the grid you can use
unset grid
The replot command updates the last plot with the recent changes on any of the configurations (axes, tics, legend, etc.). Since we will be updating the same figure a few times, we will be using this command.
Sometimes we would like to make the picture squared since the rectangle might distortion our figure. We can fix it setting the size:
set size square
replot
To go to back to the default size we can always use the command:
set autoscale
Try experimenting with the following commands:
set size ratio 0.5
replot
or
set size ratio 2
replot
What do you observe?
Labels and Title
Of course, a plot is not complete without a description of what we are seeing. We can add the labels for the axes with the following commands:
set xlabel "x"
set ylabel "f(x)"
replot
Finally, we could add a title to our figure:
set title "Plot of the function f(x)=x/2*exp(x)"
replot
Exporting a Figure
Gnuplot supports a lot of formats: png, jpg, eps, pdf, latex, svg, etc. To have a complete list, check the links below or use the command:help term
We are going to show how to export a plot to a png file with one example:
set term png
set output "plot.png"
replot
set term x11
Let's explain how this code works:
The set term png command sets the output to png.
The set output "plot.png" creates a file named "plot.png" where the plot will be saved.
We used replot to plot the last figure of the previous section, but one can plot any function or data file.
The set term x11 command brings us back the X11 output terminal and closes the file.
The output of the previous example is:
As you may have observed, the font is different from the one used in the x11 output terminal. When we switch to png, the default options were applied:
Options are 'nocrop enhanced size 640,480 font "arial,12" '
We will explain how to change fonts in the next section.
Output Terminals
In the previous example we have exported our plot to a png file using the default options. As you may imagine, the output options are highly configurable. To obtain information about all possible output terminals and their corresponding configurations, one can refer to the built-in Gnuplot help with the command
help term
Here is an output example:
Gnuplot supports a large number of output formats. These are selected by
choosing an appropriate terminal type, possibly with additional modifying
options. See `set terminal`.
This document may describe terminal types that are not available to you
because they were not configured or installed on your system. To see a list of
terminals available on a particular gnuplot installation, type 'set terminal'
with no modifiers.
Subtopics available for term:
    cairolatex    canvas      cgm        context
    corel       dpu414      dumb       dxf
    eepic       emf        emtex       epscairo
    epslatex     epson_180dpi   epson_60dpi    epson_lx800
    fig        gif        hp500c      hpdj
    hpgl       hpljii      hppj       jpeg
    latex       lua        mf        mp
    nec_cp6      okidata      pbm        pcl5
    pdfcairo     png        pngcairo     pop
    postscript    pslatex      pstex       pstricks
    push       qms        qt        sixel
    starc       svg        tandy_60dpi    tek40xx
    tek410x      texdraw      tgif       tikz
    tkcanvas     tpic       vttek       wxt
    x11        xlib       xterm
If in the subtopic option we write png and hit return we obtain the corresponding information for the png output terminal.
Note: we can look for help about other commands in the same way.
Fonts
Let us export the same figure to a png file but we will make the following changes:
Size: 1024x768 pixels
Font: Helvetica 12
To apply these changes, we set output terminal in the following way:
set term png size 1024,768 font "Helvetica,12"
Then, proceeding as in the previous example, generate a file called "plot2.png":
You may observe that the figure is bigger and it has a different font.
Remark: one can obtain more resolution using non-compressed formats. For instance, if you are working with Latex, you could generate high resolution pictures using PostScript, PDF or EPS formats. If you also want the text to appear in the same font as your latex document, then you can use epslatex.
For other text processors or office packages, you can create high resolution pictures by creating a big sized image.
Advanced Plot Formatting
For this section, we will use a new Gnuplot terminal. We will describe some of the options for plotting functions. When plotting data files we will describe a few more options.
Plotting Multiple Functions
One can plot multiple functions in the same figure using just one plot command. We will plot the sine and cosine functions in the same figure with the following command:
plot sin(x), cos(x)
We can write all the functions we want. All we need to do is to separate them with commas. If the list is too long to fit in one line (for now it will not be too long, but when we start adding options to the plots they will be), we can start a new line using a back slash and then pressing return:
plot sin(x),\
cos(x)
When displaying multiple plots in a single figure from a single or multiple data files we will also separate them using commas. This will also be useful when we write a script. (Check the corresponding sections below).
Line Types and Colors
If you do not like the default colors, or you want to use dashed lines, you can change all these options for each plot. Let us use the default options for the sine and we will use a dashed line for the cosine. To achieve our goal we will make use of the plot options:
plot sin(x),\
cos(x) dashtype 2
You could experiment changing the number 2 for 1, or you can also try increasing it. You can also specify the pattern you want by using single quotes:
plot cos(x) dashtype '-'
or mix dots and dashes:
plot cos(x) dashtype '- .'
We can add points to our lines. Use the linespoints option:
plot cos(x) dashtype 2 with linespoints
In this example we have mixed the dashed line 2 with points.
One can also modify the thickness of the line and the line type. Changing the line type changes the color and it also changes the type of point:
plot cos(x) linetype 2 dashtype 2 linewidth 2 with linespoints
The order is very important here: the command with should be placed at the end.
Note: the dashtype option was introduced in Gnuplot 5.0.
Note: to increase the number of points and obtain a plot with a better resolution, we can increase the number of samples. Increasing the number of samples will make our plot more accurate, but it may take longer to produce it. A simple example would be
set samples 100
We will give you an example with a 3D plot below.
Important: Some of the line types may change from one terminal to another.
Remark: as a final note, run the command test. A plot will appear with all the options (every output terminal will have its own test plot).
3D Plotting
For 3D figures, we need to use a different command. Let us start with a classic example for 3D plotting:
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2)
As we can observe, we used splot instead of plot. Moreover, we used two variables, x and y.
You can rotate the plot by holding a click on the figure and moving the mouse.
In the next subsections we will describe more ways to improve the visualization of the function.
Color Map and Isosamples
To add some color to our surface we can set the pm3d option:
set pm3d
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2)
As we can observe, the quality of the plot is not the best. Like when plotting functions, we can increase the number of samples used. In the case of surfaces, we also need to increase the isosamples:
set pm3d
set samples 100
set isosamples 100
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2) with pm3d
With the previous code, we can produce the same plot with more resolution:
Palette
We can change the default colors by setting a new palette. For example:
set palette gray
replot
produces a plot in gray scale color map. But we can change the palette specifying the level red, green and blue:
set palette rgbformulae 33,13,10
replot
The generated image has a color map similar to the default color map found in Matlab.
Map and Contours
Sometimes we will be more interested in seeing the contour curves or a heat map.Â
Let's start with the heat map:
set pm3d map
set size square
set samples 100
set isosamples 100
set palette rgbformulae 33,13,10
unset surface
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2) with pm3d
For this plot we just needed to add the option map after setting the pm3d.
If we want to see a contour plot instead, we can use the following example:
set pm3d map
set size square
set samples 100
set isosamples 100
set palette rgbformulae 33,13,10
set contour base
set cntrparam levels 15
unset surface
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2) palette
In this plot we have displayed the level curves of the surface and we have given them their corresponding color using the palette. A lot of options were involved in this plot:
contour base: this option enables the use of contour curves on the grid base.
cntrparam levels 15: this option sets the number of level curves to 15. One can increase or decrease the number of level curves by specifying a number (as in the example), or to set the contours in an incremental way from a minimum value to a maximum value. (See Gnuplot's help for more details).
unset surface: we disable the surface so that we can see the colors of the contour levels.
Finally, observe that in the splot command we used the option palette at the end. This option enables the contour curves to have the same color as the surface using the same palette.
Key
In the example above, the key is on top of the level curves. We will explain some of the options of the key and we will "fix" the figure above. Although we will use a 3D example, all the options apply for 2D plots.
First of all, we will change the formula in the key by sinc (which is the function we are plotting). We will reuse the code from the previous example and then we will use replot:
set pm3d map
set size square
set samples 100
set isosamples 100
set palette rgbformulae 33,13,10
set contour base
set cntrparam levels 15
unset surface
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2) palette title 'sinc'
We need to add the option title at the end of the splot command. This title is the one that will be shown in the key. If we plot more than one function, we would need to write a title for each plot).
Since the key is showing inside the box where we plot the figure, we would like to place it outside. We would like to keep it inside for some plots: if the key is on top a plot, we can always place it to the left (top, center or bottom), center (top, center or bottom), or at the right (top center or bottom). Use the help key command for more information. In our case, we want to place the key outside. We could use the command:
set key outside
replot
However, in the previous figure, the color box is on top of the key. For this particular example the command does not work well. What we will do, instead, is to place the key manually where we want. We would like to place it on the right of the figure. In this case, we could place the key using the at option:
set key at 18,10.5
replot
This produces the following figure:
Finally, we could add a title to the key box and a border for the keybox:
set key at 19,10.5 title 'Level Curves' box
replot
Note: although we do not talk about it in this tutorial, you can also set the color box anywhere you want. You can also make it horizontal or remove it.
Plotting Data Files
Plotting our data files is as easy (or as difficult) as plotting a simple function. In general, we would need to add an extra option to our plot or splot command. All you have learned until know applies to data files.
Structure of Data Files
The data files need to be structured. We will give a few of examples on how to plot data in 2D and 3D. When generating data, it is recommended to use the following three rules:
Make use of comments to organize the data: any line that starts with a # will be ignored when Gnuplot reads the data (see example below).
Values should be organized in columns separated by either a space or a tab: for instance, if we have the points of a function (x, y=f(x)), then the values of x should be placed in the first column and the corresponding values of f(x) in the second column. If we want to plot multiple functions that share the same range of values for x, we can use as many columns as functions we need:
Â
The order is, in fact, not important as one can specify the order of the variables when plotting.
For a 3D plot, the following structure is expected:
#x    y     f(x,y) (this line will be ignored)
x0Â Â Â Â y0Â Â Â Â f(x0,y0)
x0Â Â Â Â y1Â Â Â Â f(x0,y1)
x0Â Â Â Â y2Â Â Â Â f(x0,y2)
..
x0    yn    f(x0,yn)
...
x1Â Â Â Â y0Â Â Â Â f(x1,y0)
x1Â Â Â Â y1Â Â Â Â f(x1,y1)
x1Â Â Â Â y2Â Â Â Â f(x1,y2)
..
x1    yn    f(x1,yn)
...
xm    y0    f(xm,y0)
xm    y1    f(xm,y1)
xm    y2    f(xm,y2)
..
xm    yn    f(xm,yn)
xn  f(0,xn)
#t=30 (notice that we left two blank spaces)
x0Â Â f(30,x0)
x1Â Â f(30,x1)
x2Â Â f(30,x2)
..
xn  f(30,xn)
#t=60 (two blank spaces again)
x0Â Â f(60,x0)
x1Â Â f(60,x1)
x2Â Â f(60,x2)
...
xn  f(60,xn)
Plotting Data Files in 2D
To plot data in 2D we will make use of the plot command that we used for the functions. The general form of the plot command when printing a file is the following:
plot 'file' [options]
Now let us dig into these options that will help to plot our files (you could find some sample files at the end of the page, but feel free to create your own or to use your own data files).
Let us start with a simple example and then we will increase the complexity with more complicated files.
We have a file called fourpoints.txt that has the following structure:
#x f(x)
0Â Â 2
1Â Â 1
3Â Â 4
5Â Â 1.5
To plot this file we use
plot 'fourpoints.txt'
First of all, we need to point out that the figure is not empty. Let us describe what we see:
Gnuplot has adjusted the y-axis range from the minimum to the maximum values of f(x). The same happens with the x-axis.
The plotted points are on top of the plot and we cannot see them because they get confused with the frame.
To fix this problem, we change the range of both axis:
set xrange [-0.1:5.1]
set yrange [0:5]
plot 'fourpoints.txt'
Now the points are easy to see. We can observe that in the key we have the name of the file. We will change the key to "Four Points". Moreover, since one of the points has a non integer value on the y coordinate, we will change the y-tics:
set xrange[-0.5:5.1]
set yrange [0:5]
set ytics 0, 0.5, 5
plot 'fourpoints.txt' title 'Four Points'
If instead of points, you want circles, we can change the points using the option with. Using the same options as in the previous plot:
plot 'fourpoints.txt' with circles title 'Four Points'
All circles have the same size. One can specify a specific radius for all circles as an option, or each point can have its own radius: if we modify our fourpoints.txt file to have an extra column (we have called it fourpoints_bis.txt), like this:
#x   f(x)   radius
0Â Â Â Â 2Â Â Â Â 0.07
1Â Â Â Â 1Â Â Â Â 0.03
3Â Â Â Â 4Â Â Â Â 1
5Â Â Â Â 1.5 Â Â 0.1
Then, we modify slightly our previous example:
set xrange[-0.5:5.1]
set yrange [0:6.5]
set ytics 0, 0.5, 7
plot 'fourpoints_bis.txt' with circles title 'Four Points'
Do you see something strange in the picture?
This will answer your questions: from the Gnuplot manual, "The scale on y and the aspect ratio of the plot are both ignored." Thus, if one wants the circle to match the exact coordinates, then one needs to adjust the ratio manually.
We can also draw lines:
set xrange[-0.5:5.1]
set yrange [0:6.5]
set ytics 0, 0.5, 7
plot 'fourpoints_bis.txt' with lines title 'Four Points'
We can also modify lines by linespoints (we have seen this option above).
Let us reuse the fourpoints_bis.txt file and let us reinterpret the third column. Instead of considering it as a radius, let us assume that the third column corresponds to the uncertainty of the y coordinate. Then, we can plot the following figure:
set xrange[-0.5:5.1]
set yrange [0:6.5]
set ytics 0, 0.5, 7
set grid
plot 'fourpoints_bis.txt' with yerrorbars title 'Four Points'
As mentioned above, we can have multiple columns that represent different quantities and that they all are evaluated at the same range of x. For this kind of data, we need to use the option using: using allows us to choose which columns we want to use for plotting.
As an example, we have the following structure in the file sincos.txt
#x  sin(x)  cos(x)
If we want to plot the sine function, we need to use the first and second column (we count the columns from 1 to n). We specify the columns with its corresponding number and separated by a colon:
Sine
plot 'sincos.txt' using 1:2
Cosine
plot 'sincos.txt' using 1:3
We can compare the sine function against the points in our data file:
set key bottom right
plot 'sincos.txt' using 1:2,\
sin(x)
Finally, let us generate the sine and cosine plots from our data points, with a nice key, title, and labels:
set title 'Sine and Cosine functions from data'
set key title 'Functions' nobox outside top left
set xlabel 'x'
set xtics pi/2
set xrange [0:2*pi]
set size square
plot 'sincos.txt' using 1:2 with lines title 'sin(x)', \
'sincos.txt' using 1:3 dashtype 2 with lines title 'cos(x)'
In the preceding figure we have set the x-tics to be multiples of pi/2. We can actually display Greek letters using a file terminal such as png.
set term png
set output 'sincos.png'
set title 'Sine and Cosine functions from data'
set key title 'Functions' nobox outside top left
set xlabel 'x'
set xtics pi/2
set xrange [0:3*pi]
set format x '%.1P{/Symbol p}'
set size square
plot 'sincos.txt' using 1:2 with lines title 'sin(x)', \
'sincos.txt' using 1:3 dashtype 2 with lines title 'cos(x)'
set term x11
For more examples on types of plots, one can read the Gnuplot manual or check the references below. However, one quick way to explore the potential of Gnuplot is to check the Demos page http://gnuplot.sourceforge.net/demo/, because a picture is worth a thousand words.
Index
We have mentioned that one can have multiple data sets separated by blocks. To plot a block one needs the option index. Each block is identified by a number (we start counting at zero!). An example would be:
plot 'datafile' index 0 using 1:2 with lines title 'custom title'
In this example, the first block of the file "datafile" is plotted using lines.
If we introduce a number that is larger than the number of blocks in the file, Gnuplot will show an error.
Plotting Data Files in 3D
The difference between a 2D plot and a 3D plot is that we need to use a third coordinate. In this case, when using the option using, we need to add a third column. The rest of the options apply:
Use splot for 3D plotting
using 1:2:3 (or any other column numbers as needed)
with lines, points, etc.
Maps
Contours
For instance, let us plot the file sinc3D.txt that we provide.
splot 'sinc3D.txt'
Since we do not have more than three columns, splot plots the correct figure.
Now we combine the style surface setting the palette to 33,13,10. Observe the result:
set palette rgbformulae 33,13,10
splot 'sinc3D.txt' with surface
As we can see, the dots are connected generating a surface but no colors appear. To fix that, you can use the option palette:
splot 'sinc3D.txt' with surface palette
Or we could use pm3d to obtain the following result:
splot 'sinc3D.txt' with pm3d
Of course, one can plot the contours of the surface in the same way as when we plot a regular function:
set contour base
set cntrparam levels 15
splot 'sinc3D.txt' with pm3d palette
Try to plot the heat map of this surface with the pm3d option (use a new Gnuplot terminal):
set pm3d map
set size square
set palette rgbformulae 33,13,10
splot 'sinc3D.txt'
The resolution of the plot is determined by the number of points that one uses.
Plotting from Multiple Files
To finish this section about plotting from data files, we need to mention that it is possible to generate one figure with data coming from multiple files. This is how you would do it:
plot/splot 'file1.txt' [options],\
'file2.txt' [options],\
...
'fileN.txt'
Example: Suppose you have two files, name them "file1.txt" and "file2.txt", and that you want to create a 2D figure with the data from both files. The simplest command would be:
plot 'file1.txt',\
'file2.txt'
Scripting
Sometimes we need to generate a figure multiple times. It could seem a tedious job to write all the commands over and over to regenerate the same figure.
To avoid this trouble, we could create a Gnuplot script. Simplifying, a Gnuplot script is a file with all necessary commands to generate a figure. Usually, Gnuplot scripts have extension gnu.
As an example, we refer to the file "sincos.gnu". This file contains the commands that will generate the last example of Section 6.1. To generate the figure we would use the command load:
load 'sincos.gnu'
Notice that the file name is between quotes. It is important to point out that Gnuplot scripts can have comments in them. To add a comment to your script, just use the pound sign #.
Moreover, these scripts can be called from the Linux/Unix terminal through Gnuplot:
$gnuplot sincos.gnu
This option is really useful when writing a shell script!