In general, any mathematical expression accepted by C, FORTRAN, Pascal, or BASIC is valid. The precedence of these operators is determined by the specifications of the C programming language. White space (spaces and tabs) is ignored inside expressions.

Note that gnuplot uses both "real" and "integer" arithmetic, like FORTRAN and C. Integers are entered as "1", "-10", etc; reals as "1.0", "-10.0", "1e1", 3.5e-1, etc. The most important difference between the two forms is in division: division of integers truncates: 5/2 = 2; division of reals does not: 5.0/2.0 = 2.5. In mixed expressions, integers are "promoted" to reals before evaluation: 5/2e0 = 2.5. The result of division of a negative integer by a positive one may vary among compilers. Try a test like "print -5/2" to determine if your system always rounds down (-5/2 yields -3) or always rounds toward zero (-5/2 yields -2).

The integer expression "1/0" may be used to generate an "undefined" flag, which causes a point to be ignored. Or you can use the pre-defined variable NaN to achieve the same result. See using for an example.

Gnuplot can also perform simple operations on strings and string variables. For example, the expression ("A" . "B" eq "AB") evaluates as true, illustrating the string concatenation operator and the string equality operator.

A string which contains a numerical value is promoted to the corresponding integer or real value if used in a numerical expression. Thus ("3" + "4" == 7) and (6.78 == "6.78") both evaluate to true. An integer, but not a real or complex value, is promoted to a string if used in string concatenation. A typical case is the use of integers to construct file names or other strings; e.g. ("file" . 4 eq "file4") is true.

Substrings can be specified using a postfixed range descriptor [beg:end]. For example, "ABCDEF"[3:4] == "CD" and "ABCDEF"[4:*] == "DEF" The syntax "string"[beg:end] is exactly equivalent to calling the built-in string-valued function substr("string",beg,end), except that you cannot omit either beg or end from the function call.

Complex arithmetic

Arithmetic operations and most built-in functions support the use of complex arguments. Complex constants are expressed as {<real>,<imag>}, where <real> and <imag> must be numerical constants. Thus {0,1} represents 'i'. The real and imaginary components of complex value x can be extracted as real(x) and imag(x). The modulus is given by abs(x).

Gnuplot's standard 2D and 3D plot styles can plot only real values; if you need to plot a complex-valued function f(x) with non-zero imaginary components you must choose between plotting real(f(x)) or abs(f(x)). For examples of representing complex values using color, see the complex trigonometric function demos (complex_trig.dem)


Integer constants are interpreted via the C library routine strtoll(). This means that constants beginning with "0" are interpreted as octal, and constants beginning with "0x" or "0X" are interpreted as hexadecimal.

Floating point constants are interpreted via the C library routine atof().

Complex constants are expressed as {<real>,<imag>}, where <real> and <imag> must be numerical constants. For example, {3,2} represents 3 + 2i; {0,1} represents 'i' itself. The curly braces are explicitly required here.

String constants consist of any sequence of characters enclosed either in single quotes or double quotes. The distinction between single and double quotes is important. See quotes.


1 -10 0xffaabb        # integer constants
1.0 -10. 1e1 3.5e-1   # floating point constants
{1.2, -3.4}           # complex constant
"Line 1\nLine 2"      # string constant (\n is expanded to newline)
'123\n456'            # string constant (\ and n are ordinary characters)


Arguments to math functions in gnuplot can be integer, real, or complex unless otherwise noted. Functions that accept or return angles (e.g. sin(x)) treat angle values as radians, but this may be changed to degrees using the command set angles.
Math library functions
Function Arguments Returns
abs(x) any absolute value of x, | x|; same type
abs(x) complex length of x, 3#3
acos(x) any cos-1x (inverse cosine)
acosh(x) any cosh-1x (inverse hyperbolic cosine) in radians
airy(x) any Airy function Ai(x)
arg(x) complex the phase of x
asin(x) any sin-1x (inverse sin)
asinh(x) any sinh-1x (inverse hyperbolic sin) in radians
atan(x) any tan-1x (inverse tangent)
atan2(y,x) int or real tan-1(y/x) (inverse tangent)
atanh(x) any tanh-1x (inverse hyperbolic tangent) in radians
EllipticK(k) real k (-1:1) K(k) complete elliptic integral of the first kind
EllipticE(k) real k [-1:1] E(k) complete elliptic integral of the second kind
EllipticPi(n,k) real n<1, real k (-1:1) Π(n, k) complete elliptic integral of the third kind
besj0(x) int or real J0 Bessel function of x, in radians
besj1(x) int or real J1 Bessel function of x, in radians
besy0(x) int or real Y0 Bessel function of x, in radians
besy1(x) int or real Y1 Bessel function of x, in radians
ceil(x) any x, smallest integer not less than x (real part)
cos(x) any cos x, cosine of x
cosh(x) any cosh x, hyperbolic cosine of x in radians
erf(x) any erf(real(x)), error function of real(x)
erfc(x) any erfc(real(x)), 1.0 - error function of real(x)
exp(x) any ex, exponential function of x
expint(n,x) int n≥ 0, real x≥ 0 En(x) = 4#4t-ne-xt dt, exponential integral of x
floor(x) any x, largest integer not greater than x (real part)
gamma(x) any gamma(real(x)), gamma function of real(x)
ibeta(p,q,x) any ibeta(real(p, q, x)), ibeta function of real(p,q,x)
inverf(x) any inverse error function of real(x)
igamma(a,x) any igamma(real(a, x)), igamma function of real(a,x)
imag(x) complex imaginary part of x as a real number
invnorm(x) any inverse normal distribution function of real(x)
int(x) real integer part of x, truncated toward zero
lambertw(x) real Lambert W function
lgamma(x) any lgamma(real(x)), lgamma function of real(x)
log(x) any logex, natural logarithm (base e) of x
log10(x) any log10x, logarithm (base 10) of x
norm(x) any normal distribution (Gaussian) function of real(x)
rand(x) int pseudo random number in the open interval (0:1)
real(x) any real part of x
sgn(x) any 1 if x > 0, -1 if x < 0, 0 if x = 0. imag(x) ignored
sin(x) any sin x, sine of x
sinh(x) any sinh x, hyperbolic sine of x in radians
sqrt(x) any 5#5, square root of x
tan(x) any tan x, tangent of x
tanh(x) any tanh x, hyperbolic tangent of x in radians
voigt(x,y) real Voigt/Faddeeva function 6#67#78#8dt
Note: voigt(x, y) = real (faddeeva(x + iy))
Special functions from libcerf (only if available)
Function Arguments Returns
cerf(z) complex complex error function
cdawson(z) complex complex extension of Dawson's integral D(z) = 9#9e-z2erfi(z)
faddeeva(z) complex rescaled complex error function w(z) = e-z2 erfc(- iz)
erfi(x) real imaginary error function erf (x) = - i*erf (ix)
VP(x,σ,γ) real Voigt profile VP(x, σ, γ) = 10#10G(x;σ)L(x-x;γ)dx
String functions
Function Arguments Returns
gprintf("format",x,...) any string result from applying gnuplot's format parser
sprintf("format",x,...) multiple string result from C-language sprintf
strlen("string") string number of characters in string
strstrt("string","key") strings int index of first character of substring "key"
substr("string",beg,end) multiple string "string"[beg:end]
strftime("timeformat",t) any string result from applying gnuplot's time parser
strptime("timeformat",s) string seconds since year 1970 as given in string s
system("command") string string containing output stream of shell command
word("string",n) string, int returns the nth word in "string"
words("string") string returns the number of words in "string"
other gnuplot functions
Function Arguments Returns
column(x) int or string column x during datafile manipulation.
columnhead(x) int string containing first entry of column x in datafile.
exists("X") string returns 1 if a variable named X is defined, 0 otherwise.
hsv2rgb(h,s,v) h,s,v [0:1] 24bit RGB color value.
stringcolumn(x) int or string content of column x as a string.
timecolumn(N,"timeformat") int, string time data from column N during data input.
tm_hour(x) int the hour
tm_mday(x) int the day of the month
tm_min(x) int the minute
tm_mon(x) int the month
tm_sec(x) int the second
tm_wday(x) int the day of the week
tm_yday(x) int the day of the year
tm_year(x) int the year
time(x) any the current system time
valid(x) int test validity of column(x) during datafile manip.
value("name") string returns the value of the named variable.

Elliptic integrals

The EllipticK(k) function returns the complete elliptic integral of the first kind, i.e. the definite integral between 0 and pi/2 of the function (1-(k*sin(p))**2)**(-0.5). The domain of k is -1 to 1 (exclusive).

The EllipticE(k) function returns the complete elliptic integral of the second kind, i.e. the definite integral between 0 and pi/2 of the function (1-(k*sin(p))**2)**0.5. The domain of k is -1 to 1 (inclusive).

The EllipticPi(n,k) function returns the complete elliptic integral of the third kind, i.e. the definite integral between 0 and pi/2 of the function (1-(k*sin(p))**2)**(-0.5)/(1-n*sin(p)**2). The parameter n must be less than 1, while k must lie between -1 and 1 (exclusive). Note that by definition EllipticPi(0,k) == EllipticK(k) for all possible values of k.

Random number generator

The function rand() produces a sequence of pseudo-random numbers between 0 and 1 using an algorithm from P. L'Ecuyer and S. Cote, "Implementing a random number package with splitting facilities", ACM Transactions on Mathematical Software, 17:98-111 (1991).
rand(0)     returns a pseudo random number in the open interval (0:1)
            generated from the current value of two internal
            32-bit seeds.
rand(-1)    resets both seeds to a standard value.
rand(x)     for integer 0 < x < 2^31-1 sets both internal seeds
            to x.
rand({x,y}) for integer 0 < x,y < 2^31-1 sets seed1 to x and 
            seed2 to y.


B = value("A") is effectively the same as B = A, where A is the name of a user-defined variable. This is useful when the name of the variable is itself held in a string variable. See user-defined variables. It also allows you to read the name of a variable from a data file. If the argument is a numerical expression, value() returns the value of that expression. If the argument is a string that does not correspond to a currently defined variable, value() returns NaN.

Counting and extracting words

word("string",n) returns the nth word in string. For example, word("one two three",2) returns the string "two".

words("string") returns the number of words in string. For example, words(" a b c d") returns 4.

The word and words functions provide limited support for quoted strings, both single and double quotes can be used:

print words("\"double quotes\" or 'single quotes'")   # 3
A starting quote must either be preceded by a white space, or start the string. This means that apostrophes in the middle or at the end of words are considered as parts of the respective word:
print words("Alexis' phone doesn't work") # 4
Escaping quote characters is not supported. If you want to keep certain quotes, the respective section must be surrounded by the other kind of quotes:
s = "Keep \"'single quotes'\" or '\"double quotes\"'"
print word(s, 2) # 'single quotes'
print word(s, 4) # "double quotes"
Note, that in this last example the escaped quotes are necessary only for the string definition.


The operators in gnuplot are the same as the corresponding operators in the C programming language, except that all operators accept integer, real, and complex arguments, unless otherwise noted. The ** operator (exponentiation) is supported, as in FORTRAN.

Parentheses may be used to change order of evaluation.


The following is a list of all the unary operators and their usages:
Unary Operators
Symbol Example Explanation
- -a unary minus
+ +a unary plus (no-operation)
~ ~a * one's complement
! !a * logical negation
! a! * factorial
$ $3 * call arg/column during `using` manipulation
| |A| cardinality of array A

(*) Starred explanations indicate that the operator requires an integer argument.

Operator precedence is the same as in Fortran and C. As in those languages, parentheses may be used to change the order of operation. Thus -2**2 = -4, but (-2)**2 = 4.

The factorial operator returns a real number to allow a greater range.


The following is a list of all the binary operators and their usages:
Binary Operators
Symbol Example Explanation
** a**b exponentiation
* a*b multiplication
/ a/b division
% a%b * modulo
+ a+b addition
- a-b subtraction
== a==b equality
!= a!=b inequality
< a<b less than
<= a<=b less than or equal to
> a>b greater than
>= a>=b greater than or equal to
<< 0xff<<1 left shift unsigned
>> 0xff>>1 right shift unsigned
& a&b * bitwise AND
^ a^b * bitwise exclusive OR
| a|b * bitwise inclusive OR
&& a&&b * logical AND
|| a||b * logical OR
= a = b assignment
, (a,b) serial evaluation
. A.B string concatenation
eq A eq B string equality
ne A ne B string inequality

(*) Starred explanations indicate that the operator requires integer arguments. Capital letters A and B indicate that the operator requires string arguments.

Logical AND (&&) and OR (||) short-circuit the way they do in C. That is, the second && operand is not evaluated if the first is false; the second || operand is not evaluated if the first is true.

Serial evaluation occurs only in parentheses and is guaranteed to proceed in left to right order. The value of the rightmost subexpression is returned.


There is a single ternary operator:
Ternary Operator
Symbol Example Explanation
?: a?b:c ternary operation

The ternary operator behaves as it does in C. The first argument (a), which must be an integer, is evaluated. If it is true (non-zero), the second argument (b) is evaluated and returned; otherwise the third argument (c) is evaluated and returned.

The ternary operator is very useful both in constructing piecewise functions and in plotting points only when certain conditions are met.


Plot a function that is to equal sin(x) for 0 <= x < 1, 1/x for 1 <= x < 2, and undefined elsewhere:

f(x) = 0<=x && x<1 ? sin(x) : 1<=x && x<2 ? 1/x : 1/0
plot f(x)
Note that gnuplot quietly ignores undefined values, so the final branch of the function (1/0) will produce no plottable points. Note also that f(x) will be plotted as a continuous function across the discontinuity if a line style is used. To plot it discontinuously, create separate functions for the two pieces. (Parametric functions are also useful for this purpose.)

For data in a file, plot the average of the data in columns 2 and 3 against the datum in column 1, but only if the datum in column 4 is non-negative:

plot 'file' using 1:( $4<0 ? 1/0 : ($2+$3)/2 )

For an explanation of the using syntax, please see plot datafile using.


A summation expression has the form
sum [<var> = <start> : <end>] <expression>
<var> is treated as an integer variable that takes on successive integral values from <start> to <end>. For each of these, the current value of <expression> is added to a running total whose final value becomes the value of the summation expression. Examples:
print sum [i=1:10] i
# Equivalent to plot 'data' using 1:($2+$3+$4+$5+$6+...)
plot 'data' using 1 : (sum [col=2:MAXCOL] column(col))
It is not necessary that <expression> contain the variable <var>. Although <start> and <end> can be specified as variables or expressions, their value cannot be changed dynamically as a side-effect of carrying out the summation. If <end> is less than <start> then the value of the summation is zero.

Gnuplot-defined variables

Gnuplot maintains a number of read-only variables that reflect the current internal state of the program and the most recent plot. These variables begin with the prefix "GPVAL_". Examples include GPVAL_TERM, GPVAL_X_MIN, GPVAL_X_MAX, GPVAL_Y_MIN. Type show variables all to display the complete list and current values. Values related to axes parameters (ranges, log base) are values used during the last plot, not those currently set.

Example: To calculate the fractional screen coordinates of the point [X,Y]


The read-only variable GPVAL_ERRNO is set to a non-zero value if any gnuplot command terminates early due to an error. The most recent error message is stored in the string variable GPVAL_ERRMSG. Both GPVAL_ERRNO and GPVAL_ERRMSG can be cleared using the command reset errors.

Interactive terminals with mouse functionality maintain read-only variables with the prefix "MOUSE_". See mouse variables for details.

The fit mechanism uses several variables with names that begin "FIT_". It is safest to avoid using such names. When using set fit errorvariables, the error for each fitted parameter will be stored in a variable named like the parameter, but with "_err" appended. See the documentation on fit and set fit for details.

See user-defined variables, reset errors, mouse variables, and fit.

User-defined variables and functions

New user-defined variables and functions of one through twelve variables may be declared and used anywhere, including on the plot command itself.

User-defined function syntax:

<func-name>( <dummy1> {,<dummy2>} ... {,<dummy12>} ) = <expression>

where <expression> is defined in terms of <dummy1> through <dummy12>.

User-defined variable syntax:

<variable-name> = <constant-expression>


w = 2
q = floor(tan(pi/2 - 0.1))
f(x) = sin(w*x)
sinc(x) = sin(pi*x)/(pi*x)
delta(t) = (t == 0)
ramp(t) = (t > 0) ? t : 0
min(a,b) = (a < b) ? a : b
comb(n,k) = n!/(k!*(n-k)!)
len3d(x,y,z) = sqrt(x*x+y*y+z*z)
plot f(x) = sin(x*a), a = 0.2, f(x), a = 0.4, f(x)
file = "mydata.inp"
file(n) = sprintf("run_%d.dat",n)

The final two examples illustrate a user-defined string variable and a user-defined string function.

Note that the variables pi (3.14159...) and NaN (IEEE "Not a Number") are already defined. You can redefine these to something else if you really need to. The original values can be recovered by setting:

pi  = GPVAL_pi

Other variables may be defined under various gnuplot operations like mousing in interactive terminals or fitting; see gnuplot-defined variables for details.

You can check for existence of a given variable V by the exists("V") expression. For example

a = 10
if (exists("a")) print "a is defined"
if (!exists("b")) print "b is not defined"

Valid names are the same as in most programming languages: they must begin with a letter, but subsequent characters may be letters, digits, or "_".

Each function definition is made available as a special string-valued variable with the prefix 'GPFUN_'.


set label GPFUN_sinc at graph .05,.95

See show functions, functions, gnuplot-defined variables, macros, value.


Arrays are implemented as indexed lists of user variables. The elements in an array are not limited to a single type of variable. Arrays must be created explicitly before being referenced. The size of an array cannot be changed after creation. All elements are initially undefined. In most places an array element can be used instead of a named user variable. The cardinality (number of elements) of array A is given by the expression |A|.


array A[6]
A[1] = 1
A[2] = 2.0
A[3] = {3.0, 3.0}
A[4] = "four"
A[6] = A[2]**3
array B[6] = [ 1, 2.0, A[3], "four", , B[2]**3 ]
do for [i=1:6] { print A[i], B[i] }
    1 1
    2.0 2.0
    {3.0, 3.0} {3.0, 3.0}
    four four
    <undefined> <undefined>
    8.0 8.0

Note: Arrays and variables share the same namespace. For example, assignment of a string variable named FOO will destroy any previously created array with name FOO.

The name of an array can be used in a plot, splot, fit, or stats command. This is equivalent to providing a file in which column 1 holds the array index (from 1 to size), column 2 holds the value of real(A[i]) and column 3 holds the value of imag(A[i]).


array A[200]
do for [i=1:200] { A[i] = sin(i * pi/100.) }
plot A title "sin(x) in centiradians"

When plotting the imaginary component of complex array values, it may be referenced either as imag(A[$1]) or as $3. These two commands are equivalent

plot A using (real(A[$1])) : (imag(A[$1]))
plot A using 2:3

Copyright 1986 - 1993, 1998, 2004 Thomas Williams, Colin Kelley
Distributed under the gnuplot license (rights to distribute modified versions are withheld).