Gnuplot: Brief Introduction
This is a very brief overview of Gnuplot, a free function and data plotting program. Gnuplot provides an interactive command-driven interface, and it also supports command scripts. After reading this overview, you should turn to the excellent Gnuplot documentation.
Install and Run Gnuplot
Use a package manager for installation. E.g., on Windows:
winget install -e --id gnuplot.gnuplot
If gnuplot.exe
does not end up on your path, add it.
Test your installation by
entering the following in your operating system command shell.
gnuplot --version
Launch an interactive Gnuplot command shell:
gnuplot
To exit Gnuplot, enter (at the gnuplot>
prompt):
exit
To run a Gnuplot script (say, myscript.plt
)
from the operating-system command shell,
enter the following.
(The -p
option makes the window persist,
so that you can view your plots.)
gnuplot -p myscript.plt
To instead run this script at the Gnuplot prompt,
enter load "myscript.plt"
.
Two-Dimensional Plots with plot
Use plot
for 2D plotting. It plots both functions and data.
The basic syntax is:
plot {<ranges>} plot-element {, <plot-element>}
Here a plot element is a function specification or a datafile specification.
(At the gnuplot>
prompt,
enter help plot
for more details.)
Plotting Functions
To try a first function plot,
enter the following at the gnuplot>
prompt.
Note that function calls use parentheses,
and that trigonometric functions expect arguments in radians.
plot sin(x)
Naturally, many plot features may be customized.
Let us start with the plot variable and the axes ranges.
The previous plot uses
the default variable name x
and
the default plot domain [-10,10]
.
You can change them both.
plot [t=0:2*pi] sin(t)
The resulting plot frame fits the function values very tightly. Loosen this with an explicit range for the function values.
plot [t=0:2*pi] [-1.1:1.1] sin(t)
Use with points
to create same plot with points instead of lines.
plot [0:2*pi] [-1.1:1.1] sin(x) with points
The default pointtype
(pt
) and linecolor
(lc
)
are perhaps not attractive.
Enter test terminal
to display the available options.
The following plot uses blue filled circles.
plot [0:2*pi] [-1.1:1.1] sin(x) with points lc 'blue' pt 7
Here the color is given as a string, as indicated quote marks around the color. You can use single quote makrs to create raw strings and double quote marks to create strings that include escape sequences (e.g., for a newline). To illustrate, let us adjust the labels of the x and y axes, and add a two-line title for the entire plot.
set title "Example:\nFunction Plot" set xlabel "x" set ylabel "sin(x)" plot [0:2*pi] [-1.1:1.1] sin(x) with points lc 'blue' pt 7
Operators and Builtin Functions
Operators and operator precedence follow the C programming language,
except that operators usually accept integer, real, and complex arguments.
Use the **
operator for exponentiation.
Gnuplot provides many builtin functions; see the documentation. Commonly needed functions include the following.
______________________________________________________________ Function Returns ----------- ----------------------------------------------- abs absolute value ceil ceil function (convert float to int) cos cosine erf error function exp exponential function, base e floor floor function (convert float to int) int integer part (truncate towards 0) inverf inverse error function invnorm inverse normal distribution log natural logarithm (base e) norm normal Gaussian distribution function rand pseudo-random number generator round round function (convert float to nearest int) sgn sign of argument (-1,0,1) sin sine sqrt square root tan tangent ______________________________________________________________
Multiplots
Use multiplot
to place subfigures in a single frame.
reset set multiplot #prepare for multiple plots set yrange [-1.0:1.0]; set ytics (-1.0,0.0,1.0); set size 1,0.5; #each plot uses half the area set origin 0.0,0.5; set ylabel "sin(x)"; plot sin(x); set origin 0.0,0.0; set xlabel "x"; set ylabel "cos(x)"; plot cos(x); unset multiplot
Parametric Plots
The set parameteric
command turns on parametric plotting.
Use t
for the parametric variable,
and use trange
to set its range of values.
You can additionally set the allowed xrange
and yrange
.
set size ratio 1 #set aspect ratio (if desired) set xzeroaxis #draw x-axis (if desired) set yzeroaxis #draw y-axis (if desired) set parametric #turn on parametric plotting set trange [0:2*pi] #set the parameter range set xrange [-1.1:1.1] #set the x-axis range (if desired) set yrange [-1.1:1.1] #set the y-axis range (if desired) plot cos(t),sin(t) #produce the plot
Plotting Data
Plot a Single Column of Data (Run-Sequence Plot)
Suppose the file data01.csv
contains a single column of numerical data
(and nothing else).
The goal is to create a run-sequence plot (or line chart) of the data.
Do this with the following Gnuplot command.
(You may just paste the command directly into the Gnuplot terminal.)
plot 'data01.csv' using 0:1 with linespoints title "Run-Sequence Plot"
In the option using 0:1
,
0
refers to an automatically generated row index (starting from 0),
and 1
refers to the first column in the dataset (your data values).
Next, refine the plot a bit.
set title "Single Column Dataset" set xlabel "Index" set ylabel "Value" # Plot the single column dataset plot 'data01.csv' using 0:1 with linespoints title "Run-Sequence Plot"
Again, you may just paste the commands directly into the terminal.
Alternatively, store this script in plot01.plt
and load it in the Gnuplot terminal as follows.
load 'plot01.plt'
hint:: By convention, filenames are usually placed in single quotes.
Multiple Columns of Data in CSV Format
This book assumes that files with a .csv
extension
are in a restricted columnar `CSV format`_.
The first row may be a header,
providing names for the columns.
The column sparator is a single comma (and nothing else).
Run-Sequence Plots
For this example, assume data.csv
is a columnar CSV file with three columns,
and its first row is the column headers.
We want to produce three run-sequence plots in a single chart,
with a legend that uses the column headings.
set key autotitle columnhead set datafile separator "," plot for [i=1:3] 'data.csv' using 0:i with lines title columnhead(i)
Columnwise Calculations
Gnuplot can perform elementwise (column by column) operations on your data:
plot 'data.csv' using 0:(log($3+$1))
Three-Dimensional Plots with splot
For more information on 3D plots, type:
gnuplot> help splot using
More Customization
4.1 plot command customization
Plots may be displayed in one of eight styles: lines, points, linespoints, impulses, dots, steps, fsteps, histeps, errorbars, xerrorbars, yerrorbars, xyerrorbars, boxes, boxerrorbars, boxxyerrorbars, financebars, candlesticks or vector.
Labeling Plots
- Add a title:
set title "example"
- Add a label on the x-axis:
set xlabel "example"
- Add a label on the y-axis:
set ylabel "example"
- Change legend location:
set key left top
- Delete the legend:
unset key
- Place text on the plot:
set label "example" at center
- Remove all labels:
unset label
Axes
- Set the x-axis range:
set xrange [0.0:1.0]
- Set the y-axis range:
set yrange [8.5:12.0]
- Auto determine axes ranges:
set autoscale
- Use log-axes:
set logscale
- Use log-axes on y-axis:
set logscale x
- Use log-axes on y-axis:
set logscale y
- Custom x-tick marks:
set xtics (0.2,0.4,0.6,0.8,1.0)
- Custom y-tick marks:
set ytics (0.0,1.0)
- Remove custom x-tick marks:
unset xtics; set xtics
CURVE-FITTING WITH GNUPLOT
To fit the data with a function:
f1(x) = amp*sin(freq*x) # define the function to be fit amp = 3; freq = 0.5; # initial guess for parameters fit f1(x) ’data.csv’ using 1:2 via amp, freq
The curve-fit and data may now be plotted with the commands:
plot 'data.csv' using 1:2 title 'actual' with points 3, \ amp * sin(freq* x) title 'fitted'