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.
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)
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.
Examples:
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)
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^{-1}x (inverse cosine) |
acosh(x) | any | cosh^{-1}x (inverse hyperbolic cosine) in radians |
airy(x) | any | Airy function Ai(x) |
arg(x) | complex | the phase of x |
asin(x) | any | sin^{-1}x (inverse sin) |
asinh(x) | any | sinh^{-1}x (inverse hyperbolic sin) in radians |
atan(x) | any | tan^{-1}x (inverse tangent) |
atan2(y,x) | int or real | tan^{-1}(y/x) (inverse tangent) |
atanh(x) | any | tanh^{-1}x (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 | J_{0} Bessel function of x, in radians |
besj1(x) | int or real | J_{1} Bessel function of x, in radians |
besy0(x) | int or real | Y_{0} Bessel function of x, in radians |
besy1(x) | int or real | Y_{1} 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 | e^{x}, exponential function of x |
expint(n,x) | int n≥ 0, real x≥ 0 | E_{n}(x) = 4#4t^{-n}e^{-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 | log_{e}x, natural logarithm (base e) of x |
log10(x) | any | log_{10}x, 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^{-z2}erfi(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. |
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.
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.
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'") # 3A 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") # 4Escaping 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.
Parentheses may be used to change order of evaluation.
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.
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.
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.
Examples:
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.
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 55. # 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.
Example: To calculate the fractional screen coordinates of the point [X,Y]
GRAPH_X = (X - GPVAL_X_MIN) / (GPVAL_X_MAX - GPVAL_X_MIN) GRAPH_Y = (Y - GPVAL_Y_MIN) / (GPVAL_Y_MAX - GPVAL_Y_MIN) SCREEN_X = GPVAL_TERM_XMIN + GRAPH_X * (GPVAL_TERM_XMAX - GPVAL_TERM_XMIN) SCREEN_Y = GPVAL_TERM_YMIN + GRAPH_Y * (GPVAL_TERM_YMAX - GPVAL_TERM_YMIN) FRAC_X = SCREEN_X * GPVAL_TERM_SCALE / GPVAL_TERM_XSIZE FRAC_Y = SCREEN_Y * GPVAL_TERM_SCALE / GPVAL_TERM_YSIZE
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 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>
Examples:
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:
NaN = GPVAL_NaN 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_'.
Example:
set label GPFUN_sinc at graph .05,.95
See show functions, functions, gnuplot-defined variables, macros, value.
Example:
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]).
Example:
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).