[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26. plot

plot is the primary command for drawing plots with gnuplot. It creates plots of functions and data in many, many ways. plot is used to draw 2-d functions and data; splot draws 2-d projections of 3-d surfaces and data. plot and splot contain many common features; see splot for differences. Note specifically that splot's binary and matrix options do not exist for plot.

Syntax:
 
     plot {<ranges>}
          {<function> | {"<datafile>" {datafile-modifiers}}}
          {axes <axes>} {<title-spec>} {with <style>}
          {, {definitions,} <function> ...}

where either a <function> or the name of a data file enclosed in quotes is supplied. A function is a mathematical expression or a pair of mathematical expressions in parametric mode. The expressions may be defined completely or in part earlier in the stream of gnuplot commands (see user-defined).

It is also possible to define functions and parameters on the plot command itself. This is done merely by isolating them from other items with commas.

There are four possible sets of axes available; the keyword <axes> is used to select the axes for which a particular line should be scaled. x1y1 refers to the axes on the bottom and left; x2y2 to those on the top and right; x1y2 to those on the bottom and right; and x2y1 to those on the top and left. Ranges specified on the plot command apply only to the first set of axes (bottom left).

Examples:
 
     plot sin(x)
     plot f(x) = sin(x*a), a = .2, f(x), a = .4, f(x)
     plot [t=1:10] [-pi:pi*2] tan(t), \
          "data.1" using (tan($2)):($3/$4) smooth csplines \
                   axes x1y2 notitle with lines 5

36.1 data-file  
26.2 errorbars  
26.3 parametric  
26.4 ranges  
26.5 title  
26.6 with  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1 data-file

Discrete data contained in a file can be displayed by specifying the name of the data file (enclosed in single or double quotes) on the plot command line.

Syntax:
 
     plot '<file_name>' {index <index list>}
                           {every <every list>}
                           {thru <thru expression>}
                           {using <using list>}
                           {smooth <option>}

The modifiers index, every, thru, using, and smooth are discussed separately. In brief, index selects which data sets in a multi-data-set file are to be plotted, every specifies which points within a single data set are to be plotted, using determines how the columns within a single record are to be interpreted (thru is a special case of using), and smooth allows for simple interpolation and approximation. ('splot' has a similar syntax, but does not support the smooth and thru options.)

Data files should contain at least one data point per record (using can select one data point from the record). Records beginning with # (and also with ! on VMS) will be treated as comments and ignored. Each data point represents an (x,y) pair. For plots with error bars (see `set style errorbars`), each data point is (x,y,ydelta), (x,y,ylow,yhigh), (x,y,xdelta), (x,y,xlow,xhigh), or (x,y,xlow,xhigh,ylow,yhigh). In all cases, the numbers on each record of a data file must be separated by white space (one or more blanks or tabs), unless a format specifier is provided by the using option. This white space divides each record into columns.

Data may be written in exponential format with the exponent preceded by the letter e, E, d, D, q, or Q.

Only one column (the y value) need be provided. If x is omitted, gnuplot provides integer values starting at 0.

In datafiles, blank records (records with no characters other than blanks and a newline and/or carriage return) are significant--pairs of blank records separate indexes (see plot datafile index). Data separated by double blank records are treated as if they were in separate data files.

Single blank records designate discontinuities in a plot; no line will join points separated by a blank records (if they are plotted with a line style).

If autoscaling has been enabled (set autoscale), the axes are automatically extended to include all datapoints, with a whole number of tic marks if tics are being drawn. This has two consequences: i) For splot, the corner of the surface may not coincide with the corner of the base. In this case, no vertical line is drawn. ii) When plotting data with the same x range on a dual-axis graph, the x coordinates may not coincide if the x2tics are not being drawn. This is because the x axis has been autoextended to a whole number of tics, but the x2 axis has not. The following example illustrates the problem:

 
     reset; plot '-', '-'
     1 1
     19 19
     e
     1 1
     19 19
     e

26.1.1 every  
36.1.2 example datafile  
26.1.3 index  
26.1.4 smooth  
26.1.5 special-filenames  
26.1.6 thru  
26.1.7 using  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.1 every

The every keyword allows a periodic sampling of a data set to be plotted.

In the discussion a "point" is a datum defined by a single record in the file; "block" here will mean the same thing as "datablock" (see glossary).

Syntax:
 
     plot 'file' every {<point_incr>}
                         {:{<block_incr>}
                           {:{<start_point>}
                             {:{<start_block>}
                               {:{<end_point>}
                                 {:<end_block>}}}}}

The data points to be plotted are selected according to a loop from <start_point> to <end_point> with increment <point_incr> and the blocks according to a loop from <start_block> to <end_block> with increment <block_incr>.

The first datum in each block is numbered '0', as is the first block in the file.

Note that records containing unplottable information are counted.

Any of the numbers can be omitted; the increments default to unity, the start values to the first point or block, and the end values to the last point or block. If every is not specified, all points in all lines are plotted.

Examples:
 
     every :::3::3    # selects just the fourth block ('0' is first)
     every :::::9     # selects the first 10 blocks
     every 2:2        # selects every other point in every other block
     every ::5::15    # selects points 5 through 15 in each block


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.2 example datafile

This example plots the data in the file "population.dat" and a theoretical curve:

 
     pop(x) = 103*exp((1965-x)/10)
     plot [1960:1990] 'population.dat', pop(x)

The file "population.dat" might contain:

 
     # Gnu population in Antarctica since 1965
        1965   103
        1970   55
        1975   34
        1980   24
        1985   10


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.3 index

The index keyword allows only some of the data sets in a multi-data-set file to be plotted.

Syntax:
 
     plot 'file' index <m>{{:<n>}:<p>}

Data sets are separated by pairs of blank records. index <m> selects only set <m>; index <m>:<n> selects sets in the range <m> to <n>; and `index <m>:<n>:<p>` selects indices <m>, <m>+<p>, <m>+2<p>, etc., but stopping at <n>. Following C indexing, the index 0 is assigned to the first data set in the file. Specifying too large an index results in an error message. If index is not specified, all sets are plotted as a single data set.

Example:
 
     plot 'file' index 4:5


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.4 smooth

gnuplot includes a few general-purpose routines for interpolation and approximation of data; these are grouped under the smooth option. More sophisticated data processing may be performed by preprocessing the data externally or by using fit with an appropriate model.

Syntax:
 
     smooth {unique | csplines | acsplines | bezier | sbezier}

unique plots the data after making them monotonic. Each of the other routines uses the data to determine the coefficients of a continuous curve between the endpoints of the data. This curve is then plotted in the same manner as a function, that is, by finding its value at uniform intervals along the abscissa (see set samples) and connecting these points with straight line segments (if a line style is chosen).

If autoscale is in effect, the ranges will be computed such that the plotted curve lies within the borders of the graph.

If too few points are available to allow the selected option to be applied, an error message is produced. The minimum number is one for unique, four for acsplines, and three for the others.

The smooth options have no effect on function plots. The acsplines option approximates the data with a "natural smoothing spline". After the data are made monotonic in x (see smooth unique), a curve is piecewise constructed from segments of cubic polynomials whose coefficients are found by the weighting the data points; the weights are taken from the third column in the data file. That default can be modified by the third entry in the using list, e.g.,
 
     plot 'data-file' using 1:2:(1.0) smooth acsplines

Qualitatively, the absolute magnitude of the weights determines the number of segments used to construct the curve. If the weights are large, the effect of each datum is large and the curve approaches that produced by connecting consecutive points with natural cubic splines. If the weights are small, the curve is composed of fewer segments and thus is smoother; the limiting case is the single segment produced by a weighted linear least squares fit to all the data. The smoothing weight can be expressed in terms of errors as a statistical weight for a point divided by a "smoothing factor" for the curve so that (standard) errors in the file can be used as smoothing weights.

Example:
 
     sw(x,S)=1/(x*x*S)
     plot 'data_file' using 1:2:(sw($3,100)) smooth acsplines
The bezier option approximates the data with a Bezier curve of degree n (the number of data points) that connects the endpoints. The csplines option connects consecutive points by natural cubic splines after rendering the data monotonic (see smooth unique). The sbezier option first renders the data monotonic (unique) and then applies the bezier algorithm. The unique option makes the data monotonic in x; points with the same x-value are replaced by a single point having the average y-value. The resulting points are then connected by straight line segments.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.5 special-filenames

A special filename of '-' specifies that the data are inline; i.e., they follow the command. Only the data follow the command; plot options like filters, titles, and line styles remain on the 'plot' command line. This is similar to << in unix shell script, and $DECK in VMS DCL. The data are entered as though they are being read from a file, one data point per record. The letter "e" at the start of the first column terminates data entry. The using option can be applied to these data--using it to filter them through a function might make sense, but selecting columns probably doesn't!

'-' is intended for situations where it is useful to have data and commands together, e.g., when gnuplot is run as a sub-process of some front-end application. Some of the demos, for example, might use this feature. While plot options such as index and every are recognized, their use forces you to enter data that won't be used. For example, while

 
     plot '-' index 0, '-' index 1
     2
     4
     6

 
     10
     12
     14
     e
     2
     4
     6

 
     10
     12
     14
     e

does indeed work,

 
     plot '-', '-'
     2
     4
     6
     e
     10
     12
     14
     e

is a lot easier to type.

If you use '-' with replot, you may need to enter the data more than once (see replot).

A blank filename (") specifies that the previous filename should be reused. This can be useful with things like

 
     plot 'a/very/long/filename' using 1:2, '' using 1:3, '' using 1:4

(If you use both '-' and " on the same plot command, you'll need to have two sets of inline data, as in the example above.)

On some computer systems with a popen function (Unix), the datafile can be piped through a shell command by starting the file name with a '<'. For example,

 
     pop(x) = 103*exp(-x/10)
     plot "< awk '{print $1-1965, $2}' population.dat", pop(x)

would plot the same information as the first population example but with years since 1965 as the x axis. If you want to execute this example, you have to delete all comments from the data file above or substitute the following command for the first part of the command above (the part up to the comma):

 
     plot "< awk '$0 !~ /^#/ {print $1-1965, $2}' population.dat"

While this approach is most flexible, it is possible to achieve simple filtering with the using or thru keywords.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.6 thru

The thru function is provided for backward compatibility.

Syntax:
 
     plot 'file' thru f(x)

It is equivalent to:

 
     plot 'file' using 1:(f($2))

While the latter appears more complex, it is much more flexible. The more natural

 
     plot 'file' thru f(y)

also works (i.e. you can use y as the dummy variable).

thru is parsed for splot and fit but has no effect.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.1.7 using

The most common datafile modifier is using.

Syntax:
 
     plot 'file' using {<entry> {:<entry> {:<entry> ...}}} {'format'}

If a format is specified, each datafile record is read using the C library's 'scanf' function, with the specified format string. Otherwise the record is read and broken into columns at spaces or tabs. A format cannot be specified if time-format data is being used (this must be done by set data time).

The resulting array of data is then sorted into columns according to the entries. Each <entry> may be a simple column number, which selects the datum, an expression enclosed in parentheses, or empty. The expression can use $1 to access the first item read, $2 for the second item, and so on. It can also use column(x) and valid(x) where x is an arbitrary expression resulting in an integer. column(x) returns the x'th datum; valid(x) tests that the datum in the x'th column is a valid number. A column number of 0 generates a number increasing (from zero) with each point, and is reset upon encountering two blank records. A column number of -1 gives the dataline number, which starts at 0, increments at single blank records, and is reset at double blank records. A column number of -2 gives the index number, which is incremented only when two blank records are found. An empty <entry> will default to its order in the list of entries. For example, using ::4 is interpreted as using 1:2:4.

N.B.---the call command also uses $'s as a special character. See call for details about how to include a column number in a call argument list.

If the using list has but a single entry, that <entry> will be used for y and the data point number is used for x; for example, "plot 'file' using 1" is identical to "plot 'file' using 0:1". If the using list has two entries, these will be used for x and y. Additional entries are usually errors in x and/or y. See set style for details about plotting styles that make use of error information, and fit for use of error information in curve fitting.

'scanf' accepts several numerical specifications but gnuplot requires all inputs to be double-precision floating-point variables, so lf is the only permissible specifier. 'scanf' expects to see white space--a blank, tab ("\t"), newline ("\n"), or formfeed ("\f")---between numbers; anything else in the input stream must be explicitly skipped.

Note that the use of "\t", "\n", or "\f" or requires use of double-quotes rather than single-quotes.

Examples:

This creates a plot of the sum of the 2nd and 3rd data against the first: (The format string specifies comma- rather than space-separated columns.)
 
     plot 'file' using 1:($2+$3) '%lf,%lf,%lf'

In this example the data are read from the file "MyData" using a more complicated format:
 
     plot 'MyData' using "%*lf%lf%*20[^\n]%lf"

The meaning of this format is:

 
     %*lf        ignore a number
     %lf         read a double-precision number (x by default)
     %*20[^\n]   ignore 20 non-newline characters
     %lf         read a double-precision number (y by default)

One trick is to use the ternary ?: operator to filter data:

 
     plot 'file' using 1:($3>10 ? $2 : 1/0)

which plots the datum in column two against that in column one provided the datum in column three exceeds ten. 1/0 is undefined; gnuplot quietly ignores undefined points, so unsuitable points are suppressed.

In fact, you can use a constant expression for the column number, provided it doesn't start with an opening parenthesis; constructs like `using 0+(complicated expression)` can be used. The crucial point is that the expression is evaluated once if it doesn't start with a left parenthesis, or once for each data point read if it does.

If timeseries data are being used, the time can span multiple columns. The starting column should be specified. Note that the spaces within the time must be included when calculating starting columns for other data. E.g., if the first element on a line is a time with an embedded space, the y value should be specified as column three.

It should be noted that plot 'file', plot 'file' using 1:2, and `plot 'file' using ($1):($2) can be subtly different: 1) if file` has some lines with one column and some with two, the first will invent x values when they are missing, the second will quietly ignore the lines with one column, and the third will store an undefined value for lines with one point (so that in a plot with lines, no line joins points across the bad point); 2) if a line contains text at the first column, the first will abort the plot on an error, but the second and third should quietly skip the garbage.

In fact, it is often possible to plot a file with lots of lines of garbage at the top simply by specifying

 
     plot 'file' using 1:2

However, if you want to leave text in your data files, it is safer to put the comment character (#) in the first column of the text lines.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.2 errorbars

Error bars are supported for 2-d data file plots by reading one to four additional columns (or using entries); these additional values are used in different ways by the various errorbar styles.

In the default situation, gnuplot expects to see three, four, or six numbers on each line of the data file--either

 
     (x, y, ydelta),
     (x, y, ylow, yhigh),
     (x, y, xdelta),
     (x, y, xlow, xhigh),
     (x, y, xdelta, ydelta), or
     (x, y, xlow, xhigh, ylow, yhigh).

The x coordinate must be specified. The order of the numbers must be exactly as given above, though the using qualifier can manipulate the order and provide values for missing columns. For example,

 
     plot 'file' with errorbars
     plot 'file' using 1:2:(sqrt($1)) with xerrorbars
     plot 'file' using 1:2:($1-$3):($1+$3):4:5 with xyerrorbars

The last example is for a file containing an unsupported combination of relative x and absolute y errors. The using entry generates absolute x min and max from the relative error.

The y error bar is a vertical line plotted from (x, ylow) to (x, yhigh). If ydelta is specified instead of ylow and yhigh, ylow = y - ydelta and yhigh = y + ydelta are derived. If there are only two numbers on the record, yhigh and ylow are both set to y. The x error bar is a horizontal line computed in the same fashion. To get lines plotted between the data points, plot the data file twice, once with errorbars and once with lines (but remember to use the notitle option on one to avoid two entries in the key).

The error bars have crossbars at each end unless set bar is used (see `set bar` for details).

If autoscaling is on, the ranges will be adjusted to include the error bars.

See plot using, plot with, and set style for more information.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.3 parametric

When in parametric mode (set parametric) mathematical expressions must be given in pairs for plot and in triplets for splot.

Examples:
 
     plot sin(t),t**2
     splot cos(u)*cos(v),cos(u)*sin(v),sin(u)

Data files are plotted as before, except any preceding parametric function must be fully specified before a data file is given as a plot. In other words, the x parametric function (sin(t) above) and the y parametric function (t**2 above) must not be interrupted with any modifiers or data functions; doing so will generate a syntax error stating that the parametric function is not fully specified.

Other modifiers, such as with and title, may be specified only after the parametric function has been completed:

 
     plot sin(t),t**2 title 'Parametric example' with linespoints


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.4 ranges

The optional ranges specify the region of the graph that will be displayed.

Syntax:
 
     [{<dummy-var>=}{{<min>}:{<max>}}]
     [{{<min>}:{<max>}}]

The first form applies to the independent variable (xrange or trange, if in parametric mode). The second form applies to the dependent variable yrange (and xrange, too, if in parametric mode). <dummy-var> is a new name for the independent variable. (The defaults may be changed with `set dummy`.) The optional <min> and <max> terms can be constant expressions or *.

In non-parametric mode, the order in which ranges must be given is xrange and yrange.

In parametric mode, the order for the plot command is trange, xrange, and yrange. The following plot command shows setting the trange to [-pi:pi], the xrange to [-1.3:1.3] and the yrange to [-1:1] for the duration of the graph:

 
     plot [-pi:pi] [-1.3:1.3] [-1:1] sin(t),t**2

Note that the x2range and y2range cannot be specified here---set x2range and set y2range must be used.

Ranges are interpreted in the order listed above for the appropriate mode. Once all those needed are specified, no further ones must be listed, but unneeded ones cannot be skipped--use an empty range [] as a placeholder.

* can be used to allow autoscaling of either of min and max. See also set autoscale.

Ranges specified on the plot or splot command line affect only that graph; use the set xrange, set yrange, etc., commands to change the default ranges for future graphs.

With time data, you must provide the range (in the same manner as the time appears in the datafile) within quotes. gnuplot uses the timefmt string to read the value--see set timefmt.

Examples:

This uses the current ranges:
 
     plot cos(x)

This sets the x range only:
 
     plot [-10:30] sin(pi*x)/(pi*x)

This is the same, but uses t as the dummy-variable:
 
     plot [t = -10 :30]  sin(pi*t)/(pi*t)

This sets both the x and y ranges:
 
     plot [-pi:pi] [-3:3]  tan(x), 1/x

This sets only the y range, and turns off autoscaling on both axes:
 
     plot [ ] [-2:sin(5)*-8] sin(x)**besj0(x)

This sets xmax and ymin only:
 
     plot [:200] [-pi:]  exp(sin(x))

This sets the x range for a timeseries:
 
     set timefmt "%d/%m/%y %H:%M"
     plot ["1/6/93 12:00":"5/6/93 12:00"] 'timedata.dat'


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.5 title

A line title for each function and data set appears in the key, accompanied by a sample of the line and/or symbol used to represent it. It can be changed by using the title option.

Syntax:
 
     title "<title>" | notitle

where <title> is the new title of the line and must be enclosed in quotes. The quotes will not be shown in the key. A special character may be given as a backslash followed by its octal value ("\345"). The tab character "\t" is understood. Note that backslash processing occurs only for strings enclosed in double quotes--use single quotes to prevent such processing. The newline character "\n" is not processed in key entries in either type of string.

The line title and sample can be omitted from the key by using the keyword notitle. A null title (title ") is equivalent to notitle. If only the sample is wanted, use one or more blanks (title ' ').

By default the line title is the function or file name as it appears on the plot command. If it is a file name, any datafile modifiers specified will be included in the default title.

The layout of the key itself (position, title justification, etc.) can be controlled by set key. Please see set key for details.

Examples:

This plots y=x with the title 'x':
 
     plot x

This plots x squared with title "x^2" and file "data.1" with title "measured data":
 
     plot x**2 title "x^2", 'data.1' t "measured data"

This puts an untitled circular border around a polar graph:
 
     set polar; plot my_function(t), 1 notitle


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

26.6 with

Functions and data may be displayed in one of a large number of styles. The with keyword provides the means of selection.

Syntax:
 
     with <style> { {linestyle | ls <line_style>}
                    | {{linetype | lt <line_type>}
                       {linewidth | lw <line_width>}
                       {pointtype | pt <point_type>}
                       {pointsize | ps <point_size>}} }

where <style> is either lines, points, linespoints, impulses, dots, steps, fsteps, histeps, errorbars, xerrorbars, yerrorbars, xyerrorbars, boxes, boxerrorbars, boxxyerrorbars, financebars, candlesticks or vector. Some of these styles require additional information. See set style <style> for details of each style.

Default styles are chosen with the set function style and set data style commands.

By default, each function and data file will use a different line type and point type, up to the maximum number of available types. All terminal drivers support at least six different point types, and re-use them, in order, if more are required. The LaTeX driver supplies an additional six point types (all variants of a circle), and thus will only repeat after 12 curves are plotted with points. The PostScript drivers (postscript) supplies a total of 64.

If you wish to choose the line or point type for a single plot, <line_type> and <point_type> may be specified. These are positive integer constants (or expressions) that specify the line type and point type to be used for the plot. Use test to display the types available for your terminal.

You may also scale the line width and point size for a plot by using <line_width> and <point_size>, which are specified relative to the default values for each terminal. The pointsize may also be altered globally--see set pointsize for details. But note that both <point_size> as set here and as set by set pointsize multiply the default point size--their effects are not cumulative. That is, set pointsize 2; plot x w p ps 3 will use points three times default size, not six.

If you have defined specific line type/width and point type/size combinations with set linestyle, one of these may be selected by setting <line_style> to the index of the desired style.

The keywords may be abbreviated as indicated.

Note that the linewidth and pointsize options are not supported by all terminals.

Examples:

This plots sin(x) with impulses:
 
     plot sin(x) with impulses

This plots x with points, x**2 with the default:
 
     plot x*y w points, x**2 + y**2

This plots tan(x) with the default function style, file "data.1" with lines:
 
     plot [ ] [-2:5] tan(x), 'data.1' with l

This plots "leastsq.dat" with impulses:
 
     plot 'leastsq.dat' w i

This plots the data file "population" with boxes:
 
     plot 'population' with boxes

This plots "exper.dat" with errorbars and lines connecting the points (errorbars require three or four columns):
 
     plot 'exper.dat' w lines, 'exper.dat' notitle w errorbars

This plots sin(x) and cos(x) with linespoints, using the same line type but different point types:
 
     plot sin(x) with linesp lt 1 pt 3, cos(x) with linesp lt 1 pt 4

This plots file "data" with points of type 3 and twice usual size:
 
     plot 'data' with points pointtype 3 pointsize 2

This plots two data sets with lines differing only by weight:
 
     plot 'd1' t "good" w l lt 2 lw 3, 'd2' t "bad" w l lt 2 lw 1

See set style to change the default styles.


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by root l2-hrz on May, 9 2001 using texi2html