Title: " {font "name,size"} {tc }}
{lt } {fs } {at }
More than one set of histograms can appear in a single plot. In this case you
can force a gap between them, and a separate label for each set, by using the
`newhistogram` command.
For example
set style histogram cluster
plot newhistogram "Set A", 'a' using 1, '' using 2, '' using 3, \
newhistogram "Set B", 'b' using 1, '' using 2, '' using 3
The labels "Set A" and "Set B" will appear beneath the respective sets of
histograms, under the overall x axis label.
The newhistogram command can also be used to force histogram coloring to
begin with a specific color (linetype). By default colors will continue to
increment successively even across histogram boundaries. Here is an example
using the same coloring for multiple histograms
plot newhistogram "Set A" lt 4, 'a' using 1, '' using 2, '' using 3, \
newhistogram "Set B" lt 4, 'b' using 1, '' using 2, '' using 3
Similarly you can force the next histogram to begin with a specified fillstyle.
If the fillstyle is set to `pattern`, then the pattern used for filling will
be incremented automatically.
Ffigure_newhist
The `at ` option sets the x coordinate position of the following
histogram to . For example
set style histogram cluster
set style data histogram
set style fill solid 1.0 border -1
set xtic 1 offset character 0,0.3
plot newhistogram "Set A", \
'file.dat' u 1 t 1, '' u 2 t 2, \
newhistogram "Set B" at 8, \
'file.dat' u 2 t 2, '' u 2 t 2
will position the second histogram to start at x=8.
3 automated iteration over multiple columns
?automated
?histograms automated
?styles histograms automated
?plotting styles histograms automated
If you want to create a histogram from many columns of data in a single file,
it is very convenient to use the plot iteration feature. See `plot for`.
For example, to create stacked histograms of the data in columns 3 through 8
set style histogram columnstacked
plot for [i=3:8] "datafile" using i title columnhead
2 image
?plotting styles image
?style image
?image
?rgbimage
?rgbalpha
The `image`, `rgbimage`, and `rgbalpha` plotting styles all project a
uniformly sampled grid of data values onto a plane in either 2D or 3D.
The input data may be an actual bitmapped image, perhaps converted from a
standard format such as PNG, or a simple array of numerical values.
=heatmap
Ffigure_heatmap
This figure illustrates generation of a heat map from an array of scalar values.
The current palette is used to map each value onto the color assigned to the
corresponding pixel.
plot '-' matrix with image
5 4 3 1 0
2 2 0 0 1
0 0 0 1 0
0 1 2 4 3
e
e
Ffigure_rgb3D
Each pixel (data point) of the input 2D image will become a rectangle or
parallelipiped in the plot. The coordinates of each data point will determine
the center of the parallelipiped. That is, an M x N set of data will form an
image with M x N pixels. This is different from the pm3d plotting style, where
an M x N set of data will form a surface of (M-1) x (N-1) elements. The scan
directions for a binary image data grid can be further controlled by additional
keywords. See `binary keywords flipx`, `keywords center`, and `keywords rotate`.
Ffigure_scaled_image
Image data can be scaled to fill a particular rectangle within a 2D plot
coordinate system by specifying the x and y extent of each pixel.
See `binary keywords dx` and `dy`. To generate the figure at the right,
the same input image was placed multiple times, each with a specified dx, dy,
and origin. The input PNG image of a building is 50x128 pixels. The tall
building was drawn by mapping this using `dx=0.5 dy=1.5`. The short building
used a mapping `dx=0.5 dy=0.35`.
The `image` style handles input pixels containing a grayscale or color palette
value. Thus 2D plots (`plot` command) require 3 columns of data (x,y,value),
while 3D plots (`splot` command) require 4 columns of data (x,y,z,value).
The `rgbimage` style handles input pixels that are described by three separate
values for the red, green, and blue components. Thus 5D data (x,y,r,g,b) is
needed for `plot` and 6D data (x,y,z,r,g,b) for `splot`. The individual red,
green, and blue components are assumed to lie in the range [0:255].
This matches the convention used in PNG and JPEG files (see `binary filetype`).
However some data files use an alternative convention in which RGB components
are floating point values in the range [0:1]. To use the `rgbimage` style with
such data, first use the command `set rgbmax 1.0`.
The `rgbalpha` style handles input pixels that contain alpha channel
(transparency) information in addition to the red, green, and blue components.
Thus 6D data (x,y,r,g,b,a) is needed for `plot` and 7D data (x,y,z,r,g,b,a)
for `splot`. The r, g, b, and alpha components are assumed to lie in the range
[0:255]. To plot data for which RGBA components are floating point values in
the range [0:1], first use the command `set rgbmax 1.0`.
3 transparency
?image transparency
?transparency
?alpha channel
The `rgbalpha` plotting style assumes that each pixel of input data contains
an alpha value in the range [0:255]. A pixel with alpha = 0 is purely
transparent and does not alter the underlying contents of the plot. A pixel
with alpha = 255 is purely opaque. All terminal types can handle these two
extreme cases. A pixel with 0 < alpha < 255 is partially transparent.
Terminal types that do not support partial transparency will round this value
to 0 or 255.
3 image pixels
?plotting styles image pixels
?style image pixels
?image pixels
?pixels
?plotting styles image failsafe
?style image failsafe
?image failsafe
?failsafe
Some terminals use device- or library-specific optimizations to render image
data within a rectangular 2D area. This sometimes produces undesirable output,
e.g. bad clipping or scaling, missing edges. The `pixels` keyword tells
gnuplot to use generic code that renders the image pixel-by-pixel instead.
This rendering mode is slower and may result in much larger output files, but
should produce a consistent rendered view on all terminals.
(The `pixels` options was called `failsafe` mode in previous gnuplot versions.)
Example:
plot 'data' with image pixels
2 impulses
?plotting styles impulses
?style impulses
?impulses
Ffigure_impulses
The `impulses` style displays a vertical line from y=0 to the y value of each
point (2D) or from z=0 to the z value of each point (3D). Note that the y or z
values may be negative. Data from additional columns can be used to control
the color of each impulse. To use this style effectively in 3D plots, it is
useful to choose thick lines (linewidth > 1). This approximates a 3D bar chart.
1 column: y
2 columns: x y # line from [x,0] to [x,y] (2D)
3 columns: x y z # line from [x,y,0] to [x,y,z] (3D)
2 labels
?plotting styles labels
?style labels
?labels
Ffigure_labels1
The `labels` style reads coordinates and text from a data file and places
the text string at the corresponding 2D or 3D position. 3 or 4 input columns
of basic data are required. Additional input columns may be used to provide
properties that vary point by point such as text rotation angle (keywords
`rotate variable`) or color (see `textcolor variable`).
3 columns: x y string # 2D version
4 columns: x y z string # 3D version
The font, color, rotation angle and other properties of the printed text
may be specified as additional command options (see `set label`). The example
below generates a 2D plot with text labels constructed from the city whose
name is taken from column 1 of the input file, and whose geographic coordinates
are in columns 4 and 5. The font size is calculated from the value in column 3,
in this case the population.
CityName(String,Size) = sprintf("{/=%d %s}", Scale(Size), String)
plot 'cities.dat' using 5:4:(CityName(stringcolumn(1),$3)) with labels
If we did not want to adjust the font size to a different size for each city
name, the command would be much simpler:
plot 'cities.dat' using 5:4:1 with labels font "Times,8"
If the labels are marked as `hypertext` then the text only appears if the
mouse is hovering over the corresponding anchor point. See `hypertext`.
In this case you must enable the label's `point` attribute so that there is
a point to act as the hypertext anchor:
plot 'cities.dat' using 5:4:1 with labels hypertext point pt 7
Ffigure_labels2
The `labels` style can also be used in place of the `points` style when the
set of predefined point symbols is not suitable or not sufficiently flexible.
For example, here we define a set of chosen single-character symbols and assign
one of them to each point in a plot based on the value in data column 3:
set encoding utf8
symbol(z) = "∙□+⊙♠♣♡♢"[int(z):int(z)]
splot 'file' using 1:2:(symbol($3)) with labels
This example shows use of labels with variable rotation angle in column 4 and
textcolor ("tc") in column 5. Note that variable color is always taken from
the last column in the `using` specifier.
plot $Data using 1:2:3:4:5 with labels tc variable rotate variable
2 lines
?plotting styles lines
?style lines
?lines
Ffigure_lines
The `lines` style connects adjacent points with straight line segments.
It may be used in either 2D or 3D plots. The basic form requires 1, 2, or 3
columns of input data.
Additional input columns may be used to provide information such as
variable line color (see `rgbcolor variable`).
2D form (no "using" spec)
1 column: y # implicit x from row number
2 columns: x y
3D form (no "using" spec)
1 column: z # implicit x from row, y from index
3 columns: x y z
See also `linetype`, `linewidth`, and `linestyle`.
2 linespoints
?plotting styles linespoints
?style linespoints
?style lp
?linespoints
?lp
?pointinterval
?pointnumber
Ffigure_linespoints
The `linespoints` style (short form `lp`) connects adjacent points with
straight line segments and then goes back to draw a small symbol at each point.
Points are drawn with the default size determined by `set pointsize` unless a
specific point size is given in the plot command or a variable point size is
provided in an additional column of input data. Additional input columns may
also be used to provide information such as variable line color.
See `lines` and `points`.
Two keywords control whether or not every point in the plot is marked with a
symbol, `pointinterval` (short form `pi`) and `pointnumber` (short form `pn`).
`pi N` or `pi -N` tells gnuplot to only place a symbol on every Nth point.
A negative value for N will erase the portion of line segment that passes
underneath the symbol. The size of the erased portion is controlled by
`set pointintervalbox`.
`pn N` or `pn -N` tells gnuplot to label only N of the data points, evenly
spaced over the data set. As with `pi`, a negative value for N will erase the
portion of line segment that passes underneath the symbol.
2 parallelaxes
?plotting style parallelaxes
?style parallelaxes
?parallelaxes
Ffigure_parallel
Parallel axis plots can highlight correlation in a multidimensional data set.
Each input column is associated with a separately scaled vertical axis.
The column values read from each line of input are connected by line segments
drawn from axis 1 to axis 2 to axis 3 and so on. That is, each line of input
is represented by a separate line in the parallel axes plot.
It is common to use some discrete categorization to assign line colors,
allowing visual exploration of the correlation between this categorization and
the axis dimensions.
By default gnuplot will automatically determine the range and scale of the
individual axes from the input data, but the usual `set axis range` commands
can be used to customize this. See `set paxis`.
The maximum number of parallel axes is fixed at the time the program is built.
The maximum for this copy of gnuplot is reported by `show version long`.
2 points
?plotting styles points
?style points
?points
?point type
?pointtype
Ffigure_points
The `points` style displays a small symbol at each point. The command `set
pointsize` may be used to change the default size of the points. The point type
defaults to that of the linetype. See `linetype`. If no `using` spec is found
in the plot command, input data columns are interpreted implicitly.
See `style lines`.
The first 8 point types are shared by all terminals. Individual terminals may
provide a much larger number of distinct point types. Use the `test` command
to show what is provided by the current terminal settings. Alternatively any
single printable character may be given instead of a numerical point type,
as in the example below. Longer strings may be plotted using the plot style
`labels` rather than `points`.
plot sin(x) with points pt "#"
You may use any utf-8 character as the pointtype. See `utf8`.
=variable
?variable
?variable pointtype
?variable pointsize
?pointtype variable
?pointsize variable
When using the keywords `pointtype`, `pointsize`, or `linecolor` in a plot
command, the additional keyword `variable` may be given instead of a number.
In this case the corresponding properties of each point are assigned by
additional columns of input data. Variable pointsize is always taken from the
first additional column provided in a `using` spec. Variable color is always
taken from the last additional column. When plotting with style `linespoints`
it is not currently possible to specify separate colors for the lines and the
points. If all three properties are specified for each point, the order of
input data columns is thus
plot DATA using x:y:pointsize:pointtype:color \
with points lc variable pt variable ps variable
Note: for information on user-defined program variables, see `variables`.
2 steps
?plotting styles steps
?style steps
?steps
Ffigure_steps
The `steps` style is only relevant to 2D plotting. It connects consecutive
points with two line segments: the first from (x1,y1) to (x2,y1) and the
second from (x2,y1) to (x2,y2). The input column requires are the same as for
plot styles `lines` and `points`. The difference between `fsteps` and `steps`
is that `fsteps` traces first the change in y and then the change in x.
`steps` traces first the change in x and then the change in y. To fill the
area between the curve and the baseline at y=0, use `fillsteps`.
See also
^
steps demo.
^
2 rgbalpha
?plotting styles rgbalpha
?style rgbalpha
See `image`.
2 rgbimage
?plotting styles rgbimage
?style rgbimage
See `image`.
2 vectors
?plotting styles vectors
?style vectors
?vectors
Ffigure_vectors
The 2D `vectors` style draws a vector from (x,y) to (x+xdelta,y+ydelta).
The 3D `vectors` style is similar, but requires six columns of basic data.
In both cases, an additional input column (5th in 2D, 7th in 3D) may be used
to provide variable (per-datapoint) color information.
(see `linecolor` and `rgbcolor variable`).
A small arrowhead is drawn at the end of each vector.
4 columns: x y xdelta ydelta
6 columns: x y z xdelta ydelta zdelta
The keywords "with vectors" may be followed by an inline arrow style
specifications, a reference to a predefined arrow style, or a request to read
the index of the desired arrow style for each vector from a separate column.
Note: If you choose "arrowstyle variable" it will fill in all arrow properties
at the time the corresponding vector is drawn; you cannot mix this keyword with
other line or arrow style qualifiers in the plot command.
plot ... with vectors filled heads
plot ... with vectors arrowstyle 3
plot ... using 1:2:3:4:5 with vectors arrowstyle variable
Example:
plot 'file.dat' using 1:2:3:4 with vectors head filled lt 2
splot 'file.dat' using 1:2:3:(1):(1):(1) with vectors filled head lw 2
splot with vectors is supported only for `set mapping cartesian`.
`set clip one` and `set clip two` affect vectors drawn in 2D.
See `set clip` and `arrowstyle`.
2 xerrorbars
?plotting styles xerrorbars
?style xerrorbars
?xerrorbars
Ffigure_xerrorbars
The `xerrorbars` style is only relevant to 2D data plots. `xerrorbars` is
like `points`, except that a horizontal error bar is also drawn. At each point
(x,y), a line is drawn from (xlow,y) to (xhigh,y) or from (x-xdelta,y) to
(x+xdelta,y), depending on how many data columns are provided. The appearance
of the tic mark at the ends of the bar is controlled by `set errorbars`.
The basic style requires either 3 or 4 columns:
3 columns: x y xdelta
4 columns: x y xlow xhigh
An additional input column (4th or 5th) may be used to provide information
such as variable point color.
2 xyerrorbars
?plotting styles xyerrorbars
?style xyerrorbars
?xyerrorbars
Ffigure_xyerrorbars
The `xyerrorbars` style is only relevant to 2D data plots. `xyerrorbars` is
like `points`, except that horizontal and vertical error bars are also drawn.
At each point (x,y), lines are drawn from (x,y-ydelta) to (x,y+ydelta) and
from (x-xdelta,y) to (x+xdelta,y) or from (x,ylow) to (x,yhigh) and from
(xlow,y) to (xhigh,y), depending upon the number of data columns provided.
The appearance of the tic mark at the ends of the bar is controlled by
`set errorbars`. Either 4 or 6 input columns are required.
4 columns: x y xdelta ydelta
6 columns: x y xlow xhigh ylow yhigh
If data are provided in an unsupported mixed form, the `using` filter on the
`plot` command should be used to set up the appropriate form. For example,
if the data are of the form (x,y,xdelta,ylow,yhigh), then you can use
plot 'data' using 1:2:($1-$3):($1+$3):4:5 with xyerrorbars
An additional input column (5th or 7th) may be used to provide variable
(per-datapoint) color information.
2 yerrorbars
?plotting styles yerrorbars
?plotting styles errorbars
?style yerrorbars
?style errorbars
?yerrorbars
Ffigure_yerrorbars
The `yerrorbars` (or `errorbars`) style is only relevant to 2D data plots.
`yerrorbars` is like `points`, except that a vertical error bar is also drawn.
At each point (x,y), a line is drawn from (x,y-ydelta) to (x,y+ydelta) or
from (x,ylow) to (x,yhigh), depending on how many data columns are provided.
The appearance of the tic mark at the ends of the bar is controlled by
`set errorbars`.
2 columns: [implicit x] y ydelta
3 columns: x y ydelta
4 columns: x y ylow yhigh
An additional input column (4th or 5th) may be used to provide information
such as variable point color.
See also
^
errorbar demo.
^
2 xerrorlines
?plotting styles xerrorlines
?style xerrorlines
?xerrorlines
Ffigure_xerrorlines
The `xerrorlines` style is only relevant to 2D data plots.
`xerrorlines` is like `linespoints`, except that a horizontal error line is
also drawn. At each point (x,y), a line is drawn from (xlow,y) to (xhigh,y)
or from (x-xdelta,y) to (x+xdelta,y), depending on how many data columns are
provided. The appearance of the tic mark at the ends of the bar is controlled
by `set errorbars`. The basic style requires either 3 or 4 columns:
3 columns: x y xdelta
4 columns: x y xlow xhigh
An additional input column (4th or 5th) may be used to provide information
such as variable point color.
2 xyerrorlines
?plotting styles xyerrorlines
?style xyerrorlines
?xyerrorlines
Ffigure_xyerrorlines
The `xyerrorlines` style is only relevant to 2D data plots.
`xyerrorlines` is like `linespoints`, except that horizontal and vertical
error bars are also drawn. At each point (x,y), lines are drawn from
(x,y-ydelta) to (x,y+ydelta) and from (x-xdelta,y) to (x+xdelta,y) or from
(x,ylow) to (x,yhigh) and from (xlow,y) to (xhigh,y), depending upon the
number of data columns provided. The appearance of the tic mark at the ends
of the bar is controlled by `set errorbars`.
Either 4 or 6 input columns are required.
4 columns: x y xdelta ydelta
6 columns: x y xlow xhigh ylow yhigh
If data are provided in an unsupported mixed form, the `using` filter on the
`plot` command should be used to set up the appropriate form. For example,
if the data are of the form (x,y,xdelta,ylow,yhigh), then you can use
plot 'data' using 1:2:($1-$3):($1+$3):4:5 with xyerrorlines
An additional input column (5th or 7th) may be used to provide variable
(per-datapoint) color information.
2 yerrorlines
?plotting styles yerrorlines
?plotting styles errorlines
?style yerrorlines
?style errorlines
?yerrorlines
Ffigure_yerrorlines
The `yerrorlines` (or `errorlines`) style is only relevant to 2D data
plots. `yerrorlines` is like `linespoints`, except that a vertical error line
is also drawn. At each point (x,y), a line is drawn from (x,y-ydelta) to
(x,y+ydelta) or from (x,ylow) to (x,yhigh), depending on how many data columns
are provided. The appearance of the tic mark at the ends of the bar is
controlled by `set errorbars`. Either 3 or 4 input columns are required.
3 columns: x y ydelta
4 columns: x y ylow yhigh
An additional input column (4th or 5th) may be used to provide information
such as variable point color.
See also
^
errorbar demo.
^
2 zerrorfill
?plotting styles zerrorfill
?style zerrorfill
?zerrorfill
Syntax:
splot DATA using 1:2:3:4[:5] with zerrorfill {fc|fillcolor }
{lt|linetype } {}
The `zerrorfill` plot style is similar to one variant of the 2D plot style
`filledcurves`. It fills the area between two functions or data lines that
are sampled at the same x and y points. It requires 4 or 5 input columns:
4 columns: x y z zdelta
5 columns: x y z zlow zhigh
The area between zlow and zhigh is filled and then a line is drawn through the
z values. By default both the line and the fill area use the same color, but
you can change this in the splot command. The fill area properties are also
affected by the global fill style; see `set style fill`.
If there are multiple curves in the splot command each new curve may occlude
all previous curves. To get proper depth sorting so that curves can only be
occluded by curves closer to the viewer, use the command `set pm3d depthorder`.
Unfortunately this causes all the filled areas to be drawn after all of the
corresponding lines of z values. In order to see both the lines and the
depth-sorted fill areas you probably will need to make the fill areas
partially transparent or use pattern fill rather than solid fill.
The fill area in the first two examples below is the same.
splot 'data' using 1:2:3:4 with zerrorfill fillcolor "grey" lt black
splot 'data' using 1:2:3:($3-$4):($3+$4) with zerrorfill
splot '+' using 1:(const):(func1($1)):(func2($1)) with zerrorfill
splot for [k=1:5] datafile[k] with zerrorfill lt black fc lt (k+1)
This plot style can also be used to create fence plots. See `fenceplots`.
2 3D plots
?3D plots
?plotting styles 3D plots
=3D
3D plots are generated using the command `splot` rather than `plot`.
Many of the 2D plot styles (points, images, impulse, labels, vectors) can also
be used in 3D by providing an extra column of data containing z coordinate.
Some plot types (pm3d coloring, surfaces, contours) must be generated using the
`splot` command even if only a 2D projection is wanted.
3 Surface plots
?surface plots
=surface
Ffigure_surface+contours
The styles `splot with lines` and `splot with surface` both generate a surface
made from a grid of lines. Solid surfaces can be generated using the style
`splot with pm3d`. Usually the surface is displayed at some convenient viewing
angle, such that it clearly represents a 3D surface. See `set view`.
In this case the X, Y, and Z axes are all visible in the plot.
The illusion of 3D is enhanced by choosing hidden line removal or depth-sorted
surface elements. See `hidden3d` and the `depthorder` option of `set pm3d`.
The `splot` command can also calculate and draw contour lines corresponding
to constant Z values. These contour lines may be drawn onto the surface
itself, or projected onto the XY plane. See `set contour`.
Ffigure_mapcontours
3 2D projection (set view map)
?2D projection (set view map)
?projection
An important special case of the `splot` command is to map the Z coordinate
onto a 2D surface by projecting the plot along the Z axis. See `set view map`.
This plot mode can be used to generate contour plots and heat maps. This figure
shows contours plotted once with plot style `lines`, once with style `labels`.
2 Polar plots
=polar
Ffigure_polar
Polar plots are generated by changing the current coordinate system to
polar before issuing a plot command. The option `set polar` tells gnuplot to
interpret input 2D coordinates as , rather than ,.
Many, but not all, of the 2D plotting styles work in polar mode.
The figure shows a combination of plot styles `lines` and `filledcurves`.
See `set polar`, `set rrange`, `set size square`, `set theta`, `set ttics`.
2 Bee swarm plots
?beeswarm
?bee swarm
=jitter
Ffigure_jitter
"Bee swarm" plots result from applying jitter to separate overlapping points.
A typical use is to compare the distribution of y values exhibited by two or
more categories of points, where the category determines the x coordinate.
See the `set jitter` command for how to control the overlap criteria and the
displacement pattern used for jittering. The plots in the figure were created
by the same plot command but different jitter settings.
`plot $data using 1:2:1 lc variable`
2 Fence plots
?fenceplots
=zerrorfill
Ffigure_fenceplot
Fence plots combine several 2D plots by aligning their Y coordinates and
separating them from each other by a displacement along X. Filling the area
between a base value and each plot's series of Z values enhances the visual
impact of the alignment on Y and comparison on Z. There are several ways
such plots can be created in gnuplot. The simplest is to use the 5 column
variant of the `zerrorfill` style. Suppose there are separate curves z = Fi(y)
indexed by i. A fence plot is generated by `splot with zerrorfill` using
input columns
i y z_base z_base Fi(y)
1 Commands
?commands
This section lists the commands acceptable to `gnuplot` in alphabetical
order. Printed versions of this document contain all commands; the text
available interactively may not be complete. Indeed, on some systems there may
be no commands at all listed under this heading.
Note that in most cases unambiguous abbreviations for command names and their
options are permissible, i.e., "`p f(x) w li`" instead of "`plot f(x) with
lines`".
In the syntax descriptions, braces ({}) denote optional arguments and a
vertical bar (|) separates mutually exclusive choices.
2 Break
?commands break
?break
The `break` command is only meaningful inside the bracketed iteration clause
of a `do` or `while` statement. It causes the remaining statements inside the
bracketed clause to be skipped and iteration is terminated. Execution resumes
at the statement following the closing bracket. See also `continue`.
2 cd
?commands cd
?cd
The `cd` command changes the working directory.
Syntax:
cd ''
The directory name must be enclosed in quotes.
Examples:
cd 'subdir'
cd ".."
It is recommended that Windows users use single-quotes, because backslash [\]
has special significance inside double-quotes and has to be escaped.
For example,
cd "c:\newdata"
fails, but
cd 'c:\newdata'
cd "c:\\newdata"
work as expected.
2 call
?commands call
?call
The `call` command is identical to the `load` command with one exception:
the name of the file being loaded may be followed by up to nine parameters.
call "inputfile" ...
Previous versions of gnuplot performed macro-like substitution of the special
tokens $0, $1, ... $9 with the literal contents of these parameters.
This mechanism is now deprecated (see `call old-style`).
Gnuplot now provides a set of string variables ARG0, ARG1, ..., ARG9 and an
integer variable ARGC. When a `call` command is executed ARG0 is set to the
name of the input file, ARGC is set to the number of parameters present, and
ARG1 to ARG9 are loaded from the parameters that follow it on the command line.
Any existing contents of the ARG variables are saved and restored across a
`call` command.
Because the parameters are stored in ordinary string variables, they may be
dereferenced by macro expansion (analogous to the old-style deprecated syntax).
However in many cases it is more natural to use them as you would any other
variable.
3 Example
?call example
?commands call example
Call site
MYFILE = "script1.gp"
FUNC = "sin(x)"
call MYFILE FUNC 1.23 "This is a plot title"
Upon entry to the called script
ARG0 holds "script1.gp"
ARG1 holds the string "sin(x)"
ARG2 holds the string "1.23"
ARG3 holds the string "This is a plot title"
ARGC is 3
The script itself can now execute
plot @ARG1 with lines title ARG3
print ARG2 * 4.56, @ARG2 * 4.56
print "This plot produced by script ", ARG0
Notice that ARG1 must be dereferenced as a macro, but ARG2 may be dereferenced
either as a macro (yielding a numerical constant) or a variable (yielding that
same numerical value after auto-promotion of the string "1.23" to a real).
The same result could be obtained directly from a shell script by invoking
gnuplot with the `-c` command line option:
gnuplot -persist -c "script1.gp" "sin(x)" 1.23 "This is a plot title"
3 old-style
?commands call old-style
?call old-style
This describes the call mechanism used by older versions of gnuplot, now
deprecated.
call "" ...
The name of the input file must be enclosed in quotes.
As each line is read from the input file, it is scanned for the following
special character sequences: $0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $#. If found, the
sequence `$`+digit is replaced by the corresponding parameter from the `call`
command line. Quote characters are not copied and string variable substitution
is not performed. The character sequence `$#` is replaced by the number of
passed parameters. `$` followed by any other character is treated as an escape
sequence; use `$$` to get a single `$`.
Example:
If the file 'calltest.gp' contains the line:
print "argc=$# p0=$0 p1=$1 p2=$2 p3=$3 p4=$4 p5=$5 p6=$6 p7=x$7x"
entering the command:
call 'calltest.gp' "abcd" 1.2 + "'quoted'" -- "$2"
will display:
argc=7 p0=abcd p1=1.2 p2=+ p3='quoted' p4=- p5=- p6=$2 p7=xx
NOTES: This use of the `$` character conflicts both with gnuplot's own syntax
for datafile columns and with the use of `$` to indicate environmental
variables in a unix-like shell. The special sequence `$#` was mis-interpreted
as a comment delimiter in gnuplot versions 4.5 through 4.6.3. Quote characters
are ignored during substitution, so string constants are easily corrupted.
2 clear
?commands clear
?clear
=inset
?inset
The `clear` command erases the current screen or output device as specified
by `set terminal` and `set output`. This usually generates a formfeed on
hardcopy devices.
For some terminals `clear` erases only the portion of the plotting surface
defined by `set size`, so for these it can be used in conjunction with `set
multiplot` to create an inset.
Example:
set multiplot
plot sin(x)
set origin 0.5,0.5
set size 0.4,0.4
clear
plot cos(x)
unset multiplot
Please see `set multiplot`, `set size`, and `set origin` for details.
2 Continue
?commands continue
?continue
The `continue` command is only meaningful inside the bracketed iteration clause
of a `do` or `while` statement. It causes the remaining statements inside the
bracketed clause to be skipped. Execution resumes at the start of the next
iteration (if any remain in the loop condition). See also `break`.
2 Do
?commands do
?do
Syntax:
do for {
}
Execute a sequence of commands multiple times. The commands must be enclosed
in curly brackets, and the opening "{" must be on the same line as the `do`
keyword. This command cannot be used with old-style (un-bracketed) if/else
statements. See `if`. For examples of iteration specifiers, see `iteration`.
Example:
set multiplot layout 2,2
do for [name in "A B C D"] {
filename = name . ".dat"
set title sprintf("Condition %s",name)
plot filename title name
}
unset multiplot
See also `while`, `continue`, `break`.
2 evaluate
?commands evaluate
?evaluate
The `evaluate` command executes the commands given as an argument string.
Newline characters are not allowed within the string.
Syntax:
eval
This is especially useful for a repetition of similar commands.
Example:
set_label(x, y, text) \
= sprintf("set label '%s' at %f, %f point pt 5", text, x, y)
eval set_label(1., 1., 'one/one')
eval set_label(2., 1., 'two/one')
eval set_label(1., 2., 'one/two')
Please see `substitution macros` for another way to execute commands
from a string.
2 exit
?commands exit
?exit
exit
exit message "error message text"
exit status
The commands `exit` and `quit`, as well as the END-OF-FILE character (usually
Ctrl-D) terminate input from the current input stream: terminal session, pipe,
or file input (pipe). If input streams are nested (inherited `load` scripts),
then reading will continue in the parent stream. When the top level stream is
closed, the program itself will exit.
The command `exit gnuplot` will immediately and unconditionally cause gnuplot
to exit even if the input stream is multiply nested. In this case any open
output files may not be completed cleanly. Example of use:
bind "ctrl-x" "unset output; exit gnuplot"
The command `exit error "error message"` simulates a program error.
In interactive mode it prints the error message and returns to the command
line, breaking out of all nested loops or calls. In non-interactive mode
the program will exit.
When gnuplot exits to the controlling shell, the return value is not usually
informative. This variant of the command allows you to return a specific value.
exit status
See help for `batch/interactive` for more details.
2 fit
?commands fit
?fit
?least-squares
?Marquardt
The `fit` command fits a user-supplied real-valued expression to a set of
data points, using the nonlinear least-squares Marquardt-Levenberg
algorithm. There can be up to 12 independent variables, there is always 1
dependent variable, and any number of parameters can be fitted.
Optionally, error estimates can be input for weighting the data points.
The basic use of `fit` is best explained by a simple example:
f(x) = a + b*x + c*x**2
fit f(x) 'measured.dat' using 1:2 via a,b,c
plot 'measured.dat' u 1:2, f(x)
Syntax:
fit {}
'' {datafile-modifiers}
{{unitweights} | {y|xy|z}error | errors {,,...}}
via '' | {,,...}
Ranges may be specified to filter the data used in fitting.
Out-of-range data points are ignored. The syntax is
[{dummy_variable=}{}{:}],
analogous to `plot`; see `plot ranges`.
can be any valid `gnuplot` expression, although the most common is
a previously user-defined function of the form f(x) or f(x,y). It must be
real-valued.
The names of the independent variables are set by the `set dummy` command,
or in the part of the command (see below); by default, the first
two are called x and y.
Furthermore, the expression should depend on one or more variables whose
value is to be determined by the fitting procedure.
is treated as in the `plot` command. All the `plot datafile`
modifiers (`using`, `every`,...) except `smooth` are applicable to `fit`.
See `plot datafile`.
The datafile contents can be interpreted flexibly by providing a `using`
qualifier as with plot commands. For example to generate the independent
variable x as the sum of columns 2 and 3, while taking z from column 6 and
requesting equal weights:
fit ... using ($2+$3):6
In the absence of a `using` specification, the fit implicitly assumes
there is only a single independent variable. If the file itself, or the
using specification, contains only a single column of data, the line
number is taken as the independent variable.
If a `using` specification is given, there can be up to 12 independent
variables (and more if specially configured at compile time).
The `unitweights` option, which is the default, causes all data points to be
weighted equally. This can be changed by using the `errors` keyword to read
error estimates of one or more of the variables from the data file. These
error estimates are interpreted as the standard deviation s of the
corresponding variable value and used to compute a weight for the datum as
1/s**2.
In case of error estimates of the independent variables, these weights are
further multiplied by fitting function derivatives according to the
"effective variance method" (Jay Orear, Am. J. Phys., Vol. 50, 1982).
The `errors` keyword is to be followed by a comma-separated list of one or
more variable names for which errors are to be input; the dependent variable
z must always be among them, while independent variables are optional.
For each variable in this list, an additional column will be read from the
file, containing that variable's error estimate. Again, flexible
interpretation is possible by providing the `using` qualifier.
Note that the number of independent variables is thus implicitly given by the
total number of columns in the `using` qualifier, minus 1 (for the dependent
variable), minus the number of variables in the `errors` qualifier.
As an example, if one has 2 independent variables, and errors for the
first independent variable and the dependent variable, one uses
the `errors x,z` qualifier, and a `using` qualifier with 5 columns,
which are interpreted as x:y:z:sx:sz (where x and y are the independent
variables, z the dependent variable, and sx and sz the standard
deviations of x and z).
A few shorthands for the `errors` qualifier are available:
`yerrors` (for fits with 1 column of independent variable), and
`zerrors` (for the general case) are all equivalent to `errors z`,
indicating that there is a single extra column with errors of the
dependent variable.
`xyerrors`, for the case of 1 independent variable, indicates that there
are two extra columns, with errors of both the independent and the
dependent variable. In this case the errors on x and y are treated by
Orear's effective variance method.
Note that `yerror` and `xyerror` are similar in both form and interpretation
to the `yerrorlines` and `xyerrorlines` 2D plot styles.
With the command `set fit v4` the fit command syntax is compatible with
`gnuplot` version 4 and before. Then there must be two more `using`
qualifiers (z and s) than there are independent variables, unless there is
only one variable. `gnuplot` then uses the following formats, depending on
the number of columns given in the `using` specification:
z # 1 independent variable (line number)
x:z # 1 independent variable (1st column)
x:z:s # 1 independent variable (3 columns total)
x:y:z:s # 2 independent variables (4 columns total)
x1:x2:x3:z:s # 3 independent variables (5 columns total)
x1:x2:x3:...:xN:z:s # N independent variables (N+2 columns total)
Please beware that this means that you have to supply z-errors s in a fit with
two or more independent variables. If you want unit weights you need to supply
them explicitly by using e.g. then format x:y:z:(1).
The dummy variable names may be changed when specifying a range as noted above.
The first range corresponds to the first `using` spec, and so on. A range may
also be given for z (the dependent variable), in which case data points for
which f(x,...) is out of the z range will not contribute to the residual being
minimized.
Multiple datasets may be simultaneously fit with functions of one
independent variable by making y a 'pseudo-variable', e.g., the dataline
number, and fitting as two independent variables. See `fit multi-branch`.
The `via` qualifier specifies which parameters are to be optimized, either
directly, or by referencing a parameter file.
Examples:
f(x) = a*x**2 + b*x + c
g(x,y) = a*x**2 + b*y**2 + c*x*y
set fit limit 1e-6
fit f(x) 'measured.dat' via 'start.par'
fit f(x) 'measured.dat' using 3:($7-5) via 'start.par'
fit f(x) './data/trash.dat' using 1:2:3 yerror via a, b, c
fit g(x,y) 'surface.dat' using 1:2:3 via a, b, c
fit a0 + a1*x/(1 + a2*x/(1 + a3*x)) 'measured.dat' via a0,a1,a2,a3
fit a*x + b*y 'surface.dat' using 1:2:3 via a,b
fit [*:*][yaks=*:*] a*x+b*yaks 'surface.dat' u 1:2:3 via a,b
fit [][][t=*:*] a*x + b*y + c*t 'foo.dat' using 1:2:3:4 via a,b,c
set dummy x1, x2, x3, x4, x5
h(x1,x2,x3,x4,s5) = a*x1 + b*x2 + c*x3 + d*x4 + e*x5
fit h(x1,x2,x3,x4,x5) 'foo.dat' using 1:2:3:4:5:6 via a,b,c,d,e
After each iteration step, detailed information about the current state
of the fit is written to the display. The same information about the
initial and final states is written to a log file, "fit.log". This file
is always appended to, so as to not lose any previous fit history; it
should be deleted or renamed as desired. By using the command
`set fit logfile`, the name of the log file can be changed.
If activated by using `set fit errorvariables`, the error for each fitted
parameter will be stored in a variable named like the parameter, but with
"_err" appended. Thus the errors can be used as input for further
computations.
If `set fit prescale` is activated, fit parameters are prescaled by
their initial values. This helps the Marquardt-Levenberg routine
converge more quickly and reliably in cases where parameters differ
in size by several orders of magnitude.
The fit may be interrupted by pressing Ctrl-C (Ctrl-Break in wgnuplot).
After the current iteration completes, you have the option to
(1) stop the fit and accept the current parameter values,
(2) continue the fit,
(3) execute a `gnuplot` command as specified by `set fit script` or the
environment variable `FIT_SCRIPT`. The default is `replot`, so if you
had previously plotted both the data and the fitting function in one graph,
you can display the current state of the fit.
Once `fit` has finished, the `save fit` command may be used to store final
values in a file for subsequent use as a parameter file. See `save fit`
for details.
3 adjustable parameters
?commands fit parameters
?fit parameters
?commands fit adjustable_parameters
?fit adjustable_parameters
?fit_parameters
There are two ways that `via` can specify the parameters to be adjusted,
either directly on the command line or indirectly, by referencing a
parameter file. The two use different means to set initial values.
Adjustable parameters can be specified by a comma-separated list of variable
names after the `via` keyword. Any variable that is not already defined
is created with an initial value of 1.0. However, the fit is more likely
to converge rapidly if the variables have been previously declared with more
appropriate starting values.
In a parameter file, each parameter to be varied and a corresponding initial
value are specified, one per line, in the form
varname = value
Comments, marked by '#', and blank lines are permissible. The
special form
varname = value # FIXED
means that the variable is treated as a 'fixed parameter', initialized by the
parameter file, but not adjusted by `fit`. For clarity, it may be useful to
designate variables as fixed parameters so that their values are reported by
`fit`. The keyword `# FIXED` has to appear in exactly this form.
3 short introduction
?commands fit beginners_guide
?fit beginners_guide
?fit guide
?fitting
`fit` is used to find a set of parameters that 'best' fits your data to your
user-defined function. The fit is judged on the basis of the sum of the
squared differences or 'residuals' (SSR) between the input data points and
the function values, evaluated at the same places. This quantity is often
called 'chisquare' (i.e., the Greek letter chi, to the power of 2). The
algorithm attempts to minimize SSR, or more precisely, WSSR, as the residuals
are 'weighted' by the input data errors (or 1.0) before being squared;
see `fit error_estimates` for details.
That's why it is called 'least-squares fitting'. Let's look at an example
to see what is meant by 'non-linear', but first we had better go over some
terms. Here it is convenient to use z as the dependent variable for
user-defined functions of either one independent variable, z=f(x), or two
independent variables, z=f(x,y). A parameter is a user-defined variable
that `fit` will adjust, i.e., an unknown quantity in the function
declaration. Linearity/non-linearity refers to the relationship of the
dependent variable, z, to the parameters which `fit` is adjusting, not of
z to the independent variables, x and/or y. (To be technical, the
second {and higher} derivatives of the fitting function with respect to
the parameters are zero for a linear least-squares problem).
For linear least-squares (LLS), the user-defined function will be a sum of
simple functions, not involving any parameters, each multiplied by one
parameter. NLLS handles more complicated functions in which parameters can
be used in a large number of ways. An example that illustrates the
difference between linear and nonlinear least-squares is the Fourier series.
One member may be written as
z=a*sin(c*x) + b*cos(c*x).
If a and b are the unknown parameters and c is constant, then estimating
values of the parameters is a linear least-squares problem. However, if
c is an unknown parameter, the problem is nonlinear.
In the linear case, parameter values can be determined by comparatively
simple linear algebra, in one direct step. However LLS is a special case
which is also solved along with more general NLLS problems by the iterative
procedure that `gnuplot` uses. `fit` attempts to find the minimum by doing
a search. Each step (iteration) calculates WSSR with a new set of parameter
values. The Marquardt-Levenberg algorithm selects the parameter values for
the next iteration. The process continues until a preset criterion is met,
either (1) the fit has "converged" (the relative change in WSSR is less than
a certain limit, see `set fit limit`), or (2) it reaches a preset iteration
count limit (see `set fit maxiter`). The fit may also be interrupted
and subsequently halted from the keyboard (see `fit`). The user variable
FIT_CONVERGED contains 1 if the previous fit command terminated due to
convergence; it contains 0 if the previous fit terminated for any other
reason. FIT_NITER contains the number of iterations that were done during the last fit.
Often the function to be fitted will be based on a model (or theory) that
attempts to describe or predict the behaviour of the data. Then `fit` can
be used to find values for the free parameters of the model, to determine
how well the data fits the model, and to estimate an error range for each
parameter. See `fit error_estimates`.
Alternatively, in curve-fitting, functions are selected independent of
a model (on the basis of experience as to which are likely to describe
the trend of the data with the desired resolution and a minimum number
of parameters*functions.) The `fit` solution then provides an analytic
representation of the curve.
However, if all you really want is a smooth curve through your data points,
the `smooth` option to `plot` may be what you've been looking for rather
than `fit`.
3 error estimates
?commands fit error_estimates
?fit error_estimates
?fit errors
In `fit`, the term "error" is used in two different contexts, data error
estimates and parameter error estimates.
Data error estimates are used to calculate the relative weight of each data
point when determining the weighted sum of squared residuals, WSSR or
chisquare. They can affect the parameter estimates, since they determine
how much influence the deviation of each data point from the fitted function
has on the final values. Some of the `fit` output information, including
the parameter error estimates, is more meaningful if accurate data error
estimates have been provided.
The `statistical overview` describes some of the `fit` output and gives some
background for the 'practical guidelines'.
4 statistical overview
?commands fit error statistical_overview
?fit error statistical_overview
?statistical_overview
The theory of non-linear least-squares (NLLS) is generally described in terms
of a normal distribution of errors, that is, the input data is assumed to be
a sample from a population having a given mean and a Gaussian (normal)
distribution about the mean with a given standard deviation. For a sample of
sufficiently large size, and knowing the population standard deviation, one
can use the statistics of the chisquare distribution to describe a "goodness
of fit" by looking at the variable often called "chisquare". Here, it is
sufficient to say that a reduced chisquare (chisquare/degrees of freedom,
where degrees of freedom is the number of datapoints less the number of
parameters being fitted) of 1.0 is an indication that the weighted sum of
squared deviations between the fitted function and the data points is the
same as that expected for a random sample from a population characterized by
the function with the current value of the parameters and the given standard
deviations.
If the standard deviation for the population is not constant, as in counting
statistics where variance = counts, then each point should be individually
weighted when comparing the observed sum of deviations and the expected sum
of deviations.
At the conclusion `fit` reports 'stdfit', the standard deviation of the fit,
which is the rms of the residuals, and the variance of the residuals, also
called 'reduced chisquare' when the data points are weighted. The number of
degrees of freedom (the number of data points minus the number of fitted
parameters) is used in these estimates because the parameters used in
calculating the residuals of the datapoints were obtained from the same data.
If the data points have weights, `gnuplot` calculates the so-called p-value,
i.e. one minus the cumulative distribution function of the
chisquare-distribution for the number of degrees of freedom and the resulting
chisquare, see `practical_guidelines`.
These values are exported to the variables
FIT_NDF = Number of degrees of freedom
FIT_WSSR = Weighted sum-of-squares residual
FIT_STDFIT = sqrt(WSSR/NDF)
FIT_P = p-value
To estimate confidence levels for the parameters, one can use the minimum
chisquare obtained from the fit and chisquare statistics to determine the
value of chisquare corresponding to the desired confidence level, but
considerably more calculation is required to determine the combinations of
parameters which produce such values.
Rather than determine confidence intervals, `fit` reports parameter error
estimates which are readily obtained from the variance-covariance matrix
after the final iteration. By convention, these estimates are called
"standard errors" or "asymptotic standard errors", since they are calculated
in the same way as the standard errors (standard deviation of each parameter)
of a linear least-squares problem, even though the statistical conditions for
designating the quantity calculated to be a standard deviation are not
generally valid for the NLLS problem. The asymptotic standard errors are
generally over-optimistic and should not be used for determining confidence
levels, but are useful for qualitative purposes.
The final solution also produces a correlation matrix indicating correlation of
parameters in the region of the solution; The main diagonal elements,
autocorrelation, are always 1; if all parameters were independent, the
off-diagonal elements would be nearly 0. Two variables which completely
compensate each other would have an off-diagonal element of unit magnitude,
with a sign depending on whether the relation is proportional or inversely
proportional. The smaller the magnitudes of the off-diagonal elements, the
closer the estimates of the standard deviation of each parameter would be to
the asymptotic standard error.
4 practical guidelines
?commands fit error practical_guidelines
?fit error practical_guidelines
?practical_guidelines
?guidelines
If you have a basis for assigning weights to each data point, doing so lets
you make use of additional knowledge about your measurements, e.g., take into
account that some points may be more reliable than others. That may affect
the final values of the parameters.
Weighting the data provides a basis for interpreting the additional `fit`
output after the last iteration. Even if you weight each point equally,
estimating an average standard deviation rather than using a weight of 1
makes WSSR a dimensionless variable, as chisquare is by definition.
Each fit iteration will display information which can be used to evaluate
the progress of the fit. (An '*' indicates that it did not find a smaller
WSSR and is trying again.) The 'sum of squares of residuals', also called
'chisquare', is the WSSR between the data and your fitted function; `fit`
has minimized that. At this stage, with weighted data, chisquare is expected
to approach the number of degrees of freedom (data points minus parameters).
The WSSR can be used to calculate the reduced chisquare (WSSR/ndf) or stdfit,
the standard deviation of the fit, sqrt(WSSR/ndf). Both of these are
reported for the final WSSR.
If the data are unweighted, stdfit is the rms value of the deviation of the
data from the fitted function, in user units.
If you supplied valid data errors, the number of data points is large enough,
and the model is correct, the reduced chisquare should be about unity. (For
details, look up the 'chi-squared distribution' in your favorite statistics
reference.) If so, there are additional tests, beyond the scope of this
overview, for determining how well the model fits the data.
A reduced chisquare much larger than 1.0 may be due to incorrect data error
estimates, data errors not normally distributed, systematic measurement
errors, 'outliers', or an incorrect model function. A plot of the residuals,
e.g., `plot 'datafile' using 1:($2-f($1))`, may help to show any systematic
trends. Plotting both the data points and the function may help to suggest
another model.
Similarly, a reduced chisquare less than 1.0 indicates WSSR is less than that
expected for a random sample from the function with normally distributed
errors. The data error estimates may be too large, the statistical
assumptions may not be justified, or the model function may be too general,
fitting fluctuations in a particular sample in addition to the underlying
trends. In the latter case, a simpler function may be more appropriate.
The p-value of the fit is one minus the cumulative distribution function of
the chisquare-distribution for the number of degrees of freedom and the
resulting chisquare. This can serve as a measure of the goodness-of-fit.
The range of the p-value is between zero and one. A very small or large
p-value indicates that the model does not describe the data and its errors
well. As described above, this might indicate a problem with the data, its
errors or the model, or a combination thereof. A small p-value might
indicate that the errors have been underestimated and the errors of the
final parameters should thus be scaled. See also `set fit errorscaling`.
You'll have to get used to both `fit` and the kind of problems you apply it
to before you can relate the standard errors to some more practical estimates
of parameter uncertainties or evaluate the significance of the correlation
matrix.
Note that `fit`, in common with most NLLS implementations, minimizes the
weighted sum of squared distances (y-f(x))**2. It does not provide any means
to account for "errors" in the values of x, only in y. Also, any "outliers"
(data points outside the normal distribution of the model) will have an
exaggerated effect on the solution.
3 control
?commands fit control
?fit control
Settings of the `fit` command are controlled by `set fit`. The old `gnuplot`
user variables are deprecated as of version 5, see `fit control variables`.
There are a number of environment variables that can be defined to affect
`fit` before starting `gnuplot`, see `fit control environment`.
4 control variables
?commands fit control variables
?fit control variables
=FIT_LIMIT
=FIT_MAXITER
=FIT_START_LAMBDA
=FIT_LAMBDA_FACTOR
The user defined variables described here are deprecated, see `set fit`.
The default epsilon limit (1e-5) may be changed by declaring a value for
FIT_LIMIT
When the sum of squared residuals changes between two iteration steps by
a factor less than this number (epsilon), the fit is considered to have
'converged'.
The maximum number of iterations may be limited by declaring a value for
FIT_MAXITER
A value of 0 (or not defining it at all) means that there is no limit.
If you need even more control about the algorithm, and know the
Marquardt-Levenberg algorithm well, there are some more variables to
influence it. The startup value of `lambda` is normally calculated
automatically from the ML-matrix, but if you want to, you may provide
your own one with
FIT_START_LAMBDA
Specifying FIT_START_LAMBDA as zero or less will re-enable the automatic
selection. The variable
FIT_LAMBDA_FACTOR
gives the factor by which `lambda` is increased or decreased whenever
the chi-squared target function increased or decreased significantly.
Setting FIT_LAMBDA_FACTOR to zero re-enables the default factor of
10.0.
Other variables with the FIT_ prefix may be added to `fit`, so it is safer
not to use that prefix for user-defined variables.
The variables FIT_SKIP and FIT_INDEX were used by earlier releases of
`gnuplot` with a 'fit' patch called `gnufit` and are no longer available.
The datafile `every` modifier provides the functionality of FIT_SKIP.
FIT_INDEX was used for multi-branch fitting, but multi-branch fitting of
one independent variable is now done as a pseudo-3D fit in which the
second independent variable and `using` are used to specify the branch.
See `fit multi-branch`.
4 environment variables
?commands fit control environment
?fit control environment
=FIT_LOG
=FIT_SCRIPT
The environment variables must be defined before `gnuplot` is executed; how
to do so depends on your operating system.
FIT_LOG
changes the name (and/or path) of the file to which the fit log will be
written from the default of "fit.log" in the working directory. The default
value can be overwritten using the command `set fit logfile`.
FIT_SCRIPT
specifies a command that may be executed after an user interrupt. The default
is `replot`, but a `plot` or `load` command may be useful to display a plot
customized to highlight the progress of the fit. This setting can also be
changed using `set fit script`.
3 multi-branch
?commands fit multi-branch
?fit multi-branch
?multi-branch
?branch
In multi-branch fitting, multiple data sets can be simultaneously fit with
functions of one independent variable having common parameters by minimizing
the total WSSR. The function and parameters (branch) for each data set are
selected by using a 'pseudo-variable', e.g., either the dataline number (a
'column' index of -1) or the datafile index (-2), as the second independent
variable.
Example: Given two exponential decays of the form, z=f(x), each describing
a different data set but having a common decay time, estimate the values of
the parameters. If the datafile has the format x:z:s, then
f(x,y) = (y==0) ? a*exp(-x/tau) : b*exp(-x/tau)
fit f(x,y) 'datafile' using 1:-2:2:3 via a, b, tau
For a more complicated example, see the file "hexa.fnc" used by the
"fit.dem" demo.
Appropriate weighting may be required since unit weights may cause one
branch to predominate if there is a difference in the scale of the dependent
variable. Fitting each branch separately, using the multi-branch solution
as initial values, may give an indication as to the relative effect of each
branch on the joint solution.
3 starting values
?commands fit starting_values
?fit starting_values
?starting_values
Nonlinear fitting is not guaranteed to converge to the global optimum (the
solution with the smallest sum of squared residuals, SSR), and can get stuck
at a local minimum. The routine has no way to determine that; it is up to
you to judge whether this has happened.
`fit` may, and often will get "lost" if started far from a solution, where
SSR is large and changing slowly as the parameters are varied, or it may
reach a numerically unstable region (e.g., too large a number causing a
floating point overflow) which results in an "undefined value" message
or `gnuplot` halting.
To improve the chances of finding the global optimum, you should set the
starting values at least roughly in the vicinity of the solution, e.g.,
within an order of magnitude, if possible. The closer your starting values
are to the solution, the less chance of stopping at a false minimum. One way
to find starting values is to plot data and the fitting function on the same
graph and change parameter values and `replot` until reasonable similarity
is reached. The same plot is also useful to check whether the fit found a
false minimum.
Of course finding a nice-looking fit does not prove there is no "better" fit
(in either a statistical sense, characterized by an improved goodness-of-fit
criterion, or a physical sense, with a solution more consistent with the
model.) Depending on the problem, it may be desirable to `fit` with various
sets of starting values, covering a reasonable range for each parameter.
3 tips
?commands fit tips
?fit tips
?tips
Here are some tips to keep in mind to get the most out of `fit`. They're not
very organized, so you'll have to read them several times until their essence
has sunk in.
The two forms of the `via` argument to `fit` serve two largely distinct
purposes. The `via "file"` form is best used for (possibly unattended) batch
operation, where you supply the starting parameter values in a file.
The `via var1, var2, ...` form is best used interactively, where the command
history mechanism may be used to edit the list of parameters to be fitted or
to supply new startup values for the next try. This is particularly useful
for hard problems, where a direct fit to all parameters at once won't work
without good starting values. To find such, you can iterate several times,
fitting only some of the parameters, until the values are close enough to the
goal that the final fit to all parameters at once will work.
Make sure that there is no mutual dependency among parameters of the function
you are fitting. For example, don't try to fit a*exp(x+b), because
a*exp(x+b)=a*exp(b)*exp(x). Instead, fit either a*exp(x) or exp(x+b).
A technical issue: The larger the ratio of the largest and the
smallest absolute parameter values, the slower the fit will converge.
If the ratio is close to or above the inverse of the machine floating
point precision, it may take next to forever to converge, or refuse
to converge at all. You will either have to adapt your function to avoid
this, e.g., replace 'parameter' by '1e9*parameter' in the function
definition, and divide the starting value by 1e9 or use `set fit prescale`
which does this internally according to the parameter starting values.
If you can write your function as a linear combination of simple functions
weighted by the parameters to be fitted, by all means do so. That helps a
lot, because the problem is no longer nonlinear and should converge with only
a small number of iterations, perhaps just one.
Some prescriptions for analysing data, given in practical experimentation
courses, may have you first fit some functions to your data, perhaps in a
multi-step process of accounting for several aspects of the underlying
theory one by one, and then extract the information you really wanted from
the fitting parameters of those functions. With `fit`, this may often be
done in one step by writing the model function directly in terms of the
desired parameters. Transforming data can also quite often be avoided,
though sometimes at the cost of a more difficult fit problem. If you think
this contradicts the previous paragraph about simplifying the fit function,
you are correct.
A "singular matrix" message indicates that this implementation of the
Marquardt-Levenberg algorithm can't calculate parameter values for the next
iteration. Try different starting values, writing the function in another
form, or a simpler function.
Finally, a nice quote from the manual of another fitting package (fudgit),
that kind of summarizes all these issues: "Nonlinear fitting is an art!"
2 help
?commands help
?help
The `help` command displays built-in help. To specify information on a
particular topic use the syntax:
help {}
If is not specified, a short message is printed about `gnuplot`.
After help for the requested topic is given, a menu of subtopics is given;
help for a subtopic may be requested by typing its name, extending the help
request. After that subtopic has been printed, the request may be extended
again or you may go back one level to the previous topic. Eventually, the
`gnuplot` command line will return.
If a question mark (?) is given as the topic, the list of topics currently
available is printed on the screen.
2 history
?commands history
?history
The `history` command prints or saves previous commands in the history list,
or reexecutes a previous entry in the list. To modify the behavior of this
command, see `set history`.
Input lines with `history` as their first command are not stored in the
command history.
Examples:
history # show the complete history
history 5 # show last 5 entries in the history
history quiet 5 # show last 5 entries without entry numbers
history "hist.gp" # write the complete history to file hist.gp
history "hist.gp" append # append the complete history to file hist.gp
history 10 "hist.gp" # write last 10 commands to file hist.gp
history 10 "|head -5 >>diary.gp" # write 5 history commands using pipe
history ?load # show all history entries starting with "load"
history ?"set c" # like above, several words enclosed in quotes
hi !reread # execute last entry starting with "reread"
hist !"set xr" # like above, several words enclosed in quotes
hist !55 # reexecute the command at history entry 55
2 if
?commands if
?if
New syntax:
if () { ;
} else {
}
Old syntax:
if () [; else if () ...; else ...]
This version of gnuplot supports block-structured if/else statements. If the
keyword `if` or `else` is immediately followed by an opening "{", then
conditional execution applies to all statements, possibly on multiple input
lines, until a matching "}" terminates the block. If commands may be nested.
The old single-line if/else syntax is still supported, but can not be
mixed with the new block-structured syntax. See `if-old`.
3 if-old
?if if-old
?if-old
Through gnuplot version 4.4, the scope of the if/else commands was limited to
a single input line. Now a multi-line clause may be enclosed in curly brackets.
The old syntax is still honored but cannot be used inside a bracketed clause.
If no opening "{" follows the `if` keyword, the command(s) in
will be executed if is true (non-zero) or skipped if is
false (zero). Either case will consume commands on the input line until the
end of the line or an occurrence of `else`. Note that use of `;` to allow
multiple commands on the same line will _not_ end the conditionalized commands.
Examples:
pi=3
if (pi!=acos(-1)) print "?Fixing pi!"; pi=acos(-1); print pi
will display:
?Fixing pi!
3.14159265358979
but
if (1==2) print "Never see this"; print "Or this either"
will not display anything.
else:
v=0
v=v+1; if (v%2) print "2" ; else if (v%3) print "3"; else print "fred"
(repeat the last line repeatedly!)
2 for
?for
The `plot`, `splot`, `set` and `unset` commands may optionally contain an
iteration for clause. This has the effect of executing the basic command
multiple times, each time re-evaluating any expressions that make use of the
iteration control variable. Iteration of arbitrary command sequences can be
requested using the `do` command.
Two forms of iteration clause are currently supported:
for [intvar = start:end{:increment}]
for [stringvar in "A B C D"]
Examples:
plot for [filename in "A.dat B.dat C.dat"] filename using 1:2 with lines
plot for [basename in "A B C"] basename.".dat" using 1:2 with lines
set for [i = 1:10] style line i lc rgb "blue"
unset for [tag = 100:200] label tag
Nested iteration is supported:
set for [i=1:9] for [j=1:9] label i*10+j sprintf("%d",i*10+j) at i,j
See additional documentation for `iteration`, `do`.
2 import
?commands import
?import
The `import` command associates a user-defined function name with a function
exported by an external shared object. This constitutes a plugin mechanism
that extends the set of functions available in gnuplot.
Syntax:
import func(x[,y,z,...]) from "sharedobj[:symbol]"
Examples:
# make the function myfun, exported by "mylib.so" or "mylib.dll"
# available for plotting or numerical calculation in gnuplot
import myfun(x) from "mylib"
import myfun(x) from "mylib:myfun" # same as above
# make the function theirfun, defined in "theirlib.so" or "theirlib.dll"
# available under a different name
import myfun(x,y,z) from "theirlib:theirfun"
The program extends the name given for the shared object by either ".so" or
".dll" depending on the operating system, and searches for it first as a full
path name and then as a path relative to the current directory. The operating
system itself may also search any directories in LD_LIBRARY_PATH or
DYLD_LIBRARY_PATH.
2 load
?commands load
?load
The `load` command executes each line of the specified input file as if it
had been typed in interactively. Files created by the `save` command can
later be `load`ed. Any text file containing valid commands can be created
and then executed by the `load` command. Files being `load`ed may themselves
contain `load` or `call` commands. See `comments` for information about
comments in commands. To `load` with arguments, see `call`.
Syntax:
load ""
The name of the input file must be enclosed in quotes.
The special filename "-" may be used to `load` commands from standard input.
This allows a `gnuplot` command file to accept some commands from standard
input. Please see help for `batch/interactive` for more details.
On some systems which support a popen function (Unix), the load file can be
read from a pipe by starting the file name with a '<'.
Examples:
load 'work.gnu'
load "func.dat"
load "< loadfile_generator.sh"
The `load` command is performed implicitly on any file names given as
arguments to `gnuplot`. These are loaded in the order specified, and
then `gnuplot` exits.
2 lower
See `raise`.
2 pause
?commands pause
?pause
?pause mouse
The `pause` command displays any text associated with the command and then
waits a specified amount of time or until the carriage return is pressed.
`pause` is especially useful in conjunction with `load` files.
Syntax:
pause