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.
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.
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)
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 | |x|, absolute value of x; same type |
abs(x) | complex | length of x, √( Re(x)2 + Im(x)2 ) |
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 in (-1:1) | K(k) complete elliptic integral of the first kind |
EllipticE(k) | real k in [-1:1] | E(k) complete elliptic integral of the second kind |
EllipticPi(n,k) | real n<1, real k in (-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) | radians | cos x, cosine of x |
cosh(x) | any | cosh x, hyperbolic cosine of x in radians |
erf(x) | any | erf(Re(x)), error function of real(x) |
erfc(x) | any | erfc(Re(x)), 1.0 - error function of real(x) |
exp(x) | any | ex, exponential function of x |
expint(n,x) | any | En(x), exponential integral function of x |
floor(x) | any | ⌊x⌋, largest integer not greater than x (real part) |
gamma(x) | any | Γ(Re(x)), gamma function of real(x) |
ibeta(p,q,x) | any | ibeta(Re(p,q,x)), ibeta function of real(p,q,x) |
inverf(x) | any | inverse error function real(x) |
igamma(a,x) | any | igamma(Re(a,x)), igamma function of real(a,x) |
imag(x) | complex | Im(x), imaginary part of x as a real number |
invnorm(x) | any | inverse normal distribution function real(x) |
int(x) | real | integer part of x, truncated toward zero |
lambertw(x) | real | Lambert W function |
lgamma(x) | any | lgamma(Re(x)), lgamma function of real(x) |
log(x) | any | ln x, natural logarithm (base e) of x |
log10(x) | any | log10 x, logarithm (base 10) of x |
norm(x) | any | norm(x), normal distribution function of real(x) |
rand(x) | int | pseudo random number in the interval (0:1) |
real(x) | any | Re(x), real part of x |
sgn(x) | any | 1 if x > 0, -1 if x < 0, 0 if x = 0. ℑ(x) ignored |
sin(x) | any | sin x, sine of x |
sinh(x) | any | sinh x, hyperbolic sine of x in radians |
sqrt(x) | any | √x, 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 | convolution of Gaussian and Lorentzian |
Special functions from libcerf (only if available) | ||
---|---|---|
Function | Arguments | Returns |
cerf(z) | complex | complex error function |
cdawson(z) | complex | complex Dawson's integral |
faddeeva(z) | complex | rescaled complex error function w(z) = exp(-z²) × erfc(-iz) |
erfi(x) | real | imaginary error function erfi(x) = -i × erf(ix) |
VP(x,sigma,gamma) | real | Voigt profile |
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 | contents of column x during data input. |
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 in [0:1] | converts HSV color to 24bit RGB color. |
stringcolumn(x) | int | content column x as a string. |
timecolumn(N,format) | int, string | time data in 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 current value of the named variable. |
The abs(x) function returns the absolute value of its argument. The returned value is of the same type as the argument.
For complex arguments, abs(x) is defined as the length of x in the complex plane [i.e., sqrt(real(x)**2 + imag(x)**2) ]. This is also known as the norm or complex modulus of x.
The acos(x) function returns the arc cosine (inverse cosine) of its argument. acos returns its argument in radians or degrees, as selected by set angles.
The acosh(x) function returns the inverse hyperbolic cosine of its argument in radians.
The airy(x) function returns the value of the Airy function Ai(x) of its argument. The function Ai(x) is that solution of the equation y'' - x y = 0 which is everywhere finite. If the argument is complex, its imaginary part is ignored.
The arg(x) function returns the phase of a complex number in radians or degrees, as selected by set angles.
The asin(x) function returns the arc sin (inverse sin) of its argument. asin returns its argument in radians or degrees, as selected by set angles.
The asinh(x) function returns the inverse hyperbolic sin of its argument in radians.
The atan(x) function returns the arc tangent (inverse tangent) of its argument. atan returns its argument in radians or degrees, as selected by set angles.
The atan2(y,x) function returns the arc tangent (inverse tangent) of the ratio of the real parts of its arguments. atan2 returns its argument in radians or degrees, as selected by set angles, in the correct quadrant.
The atanh(x) function returns the inverse hyperbolic tangent of its argument in radians.
The EllipticK(k) function returns the complete elliptic integral of the first kind. See elliptic integrals for more details.
The EllipticE(k) function returns the complete elliptic integral of the second kind. See elliptic integrals for more details.
The EllipticPi(n,k) function returns the complete elliptic integral of the third kind. See elliptic integrals for more details.
The besj0(x) function returns the J0th Bessel function of its argument. besj0 expects its argument to be in radians.
The besj1(x) function returns the J1st Bessel function of its argument. besj1 expects its argument to be in radians.
The besy0(x) function returns the Y0th Bessel function of its argument. besy0 expects its argument to be in radians.
The besy1(x) function returns the Y1st Bessel function of its argument. besy1 expects its argument to be in radians.
The ceil(x) function returns the smallest integer that is not less than its argument. For complex numbers, ceil returns the smallest integer not less than the real part of its argument.
The cos(x) function returns the cosine of its argument. cos accepts its argument in radians or degrees, as selected by set angles.
The cosh(x) function returns the hyperbolic cosine of its argument. cosh expects its argument to be in radians.
The erf(x) function returns the error function of the real part of its argument. If the argument is a complex value, the imaginary component is ignored. See erfc, inverf, and norm.
The erfc(x) function returns 1.0 - the error function of the real part of its argument. If the argument is a complex value, the imaginary component is ignored. See erf, inverf, and norm.
The exp(x) function returns the exponential function of its argument (e raised to the power of its argument). On some implementations (notably suns), exp(-x) returns undefined for very large x. A user-defined function like safe(x) = x<-100 ? 0 : exp(x) might prove useful in these cases.
The expint(n,x) function returns the exponential integral of the real part of its argument: integral from 1 to infinity of t^(-n) e^(-tx) dt. n must be a nonnegative integer, x>=0, and either x>0 or n>1.
The floor(x) function returns the largest integer not greater than its argument. For complex numbers, floor returns the largest integer not greater than the real part of its argument.
The gamma(x) function returns the gamma function of the real part of its argument. For integer n, gamma(n+1) = n!. If the argument is a complex value, the imaginary component is ignored.
The ibeta(p,q,x) function returns the incomplete beta function of the real parts of its arguments. p, q > 0 and x in [0:1]. If the arguments are complex, the imaginary components are ignored. The function is approximated by the method of continued fractions (Abramowitz and Stegun, 1964). The approximation is only accurate in the region x < (p-1)/(p+q-2).
The inverf(x) function returns the inverse error function of the real part of its argument. See erf and invnorm.
The igamma(a,x) function returns the normalized incomplete gamma function of the real parts of its arguments, where a > 0 and x >= 0. The standard notation is P(a,x), e.g. Abramowitz and Stegun (6.5.1), with limiting value of 1 as x approaches infinity. If the arguments are complex, the imaginary components are ignored.
The imag(x) function returns the imaginary part of its argument as a real number.
The invnorm(x) function returns the inverse cumulative normal (Gaussian) distribution function of the real part of its argument. See norm.
The int(x) function returns the integer part of its argument, truncated toward zero.
The lambertw(x) function returns the value of the principal branch of Lambert's W function, which is defined by the equation (W(x)*exp(W(x))=x. x must be a real number with x >= -exp(-1).
The lgamma(x) function returns the natural logarithm of the gamma function of the real part of its argument. If the argument is a complex value, the imaginary component is ignored.
The log(x) function returns the natural logarithm (base e) of its argument. See log10.
The log10(x) function returns the logarithm (base 10) of its argument.
The norm(x) function returns the cumulative normal (Gaussian) distribution function of the real part of its argument. See invnorm, erf and erfc.
The rand(x) function returns a pseudo random number in the interval (0:1). See random for more details.
The real(x) function returns the real part of its argument.
The sgn(x) function returns 1 if its argument is positive, -1 if its argument is negative, and 0 if its argument is 0. If the argument is a complex value, the imaginary component is ignored.
The sin(x) function returns the sine of its argument. sin expects its argument to be in radians or degrees, as selected by set angles.
The sinh(x) function returns the hyperbolic sine of its argument. sinh expects its argument to be in radians.
The sqrt(x) function returns the square root of its argument. If the x is a complex value, this always returns the root with positive real part.
The tan(x) function returns the tangent of its argument. tan expects its argument to be in radians or degrees, as selected by set angles.
The tanh(x) function returns the hyperbolic tangent of its argument. tanh expects its argument to be in radians.
The function voigt(x,y) returns an approximation to the Voigt/Faddeeva function used in spectral analysis. The approximation is accurate to one part in 10^4. If the libcerf routines are available, the re_w_of_z() routine is used to provide a more accurate value. Note that voigt(x,y) = real(faddeeva( x + y*{0,1} )).
cerf(z) is the complex version of the error function erf(x)
cdawson(z) returns Dawson's Integral evaluated for the complex argument z. cdawson(z) = sqrt(pi)/2 * exp(-z^2) * erfi(z)
The faddeeva(z) function returns the rescaled complex error function faddeeva(z) = exp(-z^2) * erfc(-i*z) This corresponds to Eqs 7.1.3 and 7.1.4 of Abramowitz and Stegun.
Imaginary error function erfi(x) = -i * erf(ix)
VP(x,sigma,gamma) corresponds to the Voigt profile defined by convolution of a Gaussian G(x;sigma) with a Lorentzian L(x;gamma).
gprintf("format",x) applies gnuplot's own format specifiers to the single variable x and returns the resulting string. If you want standard C-language format specifiers, you must instead use sprintf("format",x). See format specifiers.
sprintf("format",var1,var2,...) applies standard C-language format specifiers to multiple arguments and returns the resulting string. If you want to use gnuplot's own format specifiers, you must instead call gprintf(). For information on sprintf format specifiers, please see standard C-language documentation or the unix sprintf man page.
strlen("string") returns the number of characters in a string taking into account the current encoding. If the current encoding supports multibyte characters (SJIS UTF8), this may be less than the number of bytes in the string. If the string contains multibyte UTF8 characters but the current encoding is set set to something other than UTF8, strlen("utf8string") will return a value that is larger than the actual number of characters.
strstrt("string","key") searches for the character string "key" in "string" and returns the index to the first character of "key". If "key" is not found, returns 0. Similar to C library function strstr except that it returns an index rather than a string pointer. strstrt("hayneedlestack","needle") = 4.
substr("string",beg,end) returns the substring consisting of characters beg through end of the original string. This is exactly equivalent to the expression "string"[beg:end] except that you do not have the option of omitting beg or end.
strftime("timeformat",t) applies the timeformat specifiers to the time t given in seconds since the year 1970. See time_specifiers and strptime.
strptime("timeformat",s) reads the time from the string s using the timeformat specifiers and converts it into seconds since the year 1970. See time_specifiers and strftime.
system("command") executes "command" using the standard shell and returns the resulting character stream from stdout as string variable. One optional trailing newline is ignored.
This can be used to import external functions into gnuplot scripts using 'f(x) = real(system(sprintf("somecommand %f", x)))'.
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.
column(x) may be used only as part of a plot, splot, or stats command. It evaluates to the numerical value of the content of column x. See plot datafile using.
columnhead(x) may only be used as part of a plot, splot, or stats command. It evaluates to a string containing the content of column x in the first line of a data file. See plot datafile using.
The argument to exists() is a string constant or a string variable; if the string contains the name of a defined variable, the function returns 1. Otherwise the function returns 0.
The hsv2rgb(h,s,v) function converts HSV (Hue/Saturation/Value) triplet to an equivalent RGB value.
stringcolumn(x) may be used only in expressions as part of using manipulations to fits or datafile plots. It returns the content of column x as a string variable. strcol(x) is shorthand for stringcolumn(x). See plot datafile using.
timecolumn(N,"timeformat") may be used only in expressions as part of using manipulations to fits or datafile plots. See plot datafile using.
It reads string data starting at column N as a time/date value and uses "timeformat" to interpret this as "seconds since the epoch" to millisecond precision. Note: prior to version 5 this function took only a single parameter and worked only for columns that contained purely an axis coordinate.
The tm_hour(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the hour (an integer in the range 0--23) as a real.
The tm_mday(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the day of the month (an integer in the range 1--31) as a real.
The tm_min(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the minute (an integer in the range 0--59) as a real.
The tm_mon(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the month (an integer in the range 0--11) as a real.
The tm_sec(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the second (an integer in the range 0--59) as a real.
The tm_wday(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the day of the week (an integer in the range 0--6) as a real.
The tm_yday(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the day of the year (an integer in the range 1--366) as a real.
The tm_year(x) function interprets its argument as a time, in seconds from 1 Jan 1970. It returns the year (an integer) as a real.
The time(x) function returns the current system time. This value can be converted to a date string with the strftime function, or it can be used in conjunction with timecolumn to generate relative time/date plots. The type of the argument determines what is returned. If the argument is an integer, time() returns the current time as an integer, in seconds from 1 Jan 1970. If the argument is real (or complex), the result is real as well. If the argument is a string, it is assumed to be a format string, and it is passed to strftime to provide a formatted time string.
valid(x) may be used only in expressions as part of using manipulations to fits or datafile plots. See plot datafile using.
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.
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.
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 preceeded 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:
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:
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:
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.
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 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.
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]
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.
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>
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.
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|.
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