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.
Starting a new histogram will normally add a blank entry to the key, so that
titles from this set of histogram components will be separated from those of
the previous histogram. This blank line may be undesirable if the components
have no individual titles. It can be suppressed by modifying the style with
`set style histogram nokeyseparators`.
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
?with histograms 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
3 histogram color assignments
?with histograms colors
?histograms colors
?styles histograms colors
?plotting styles histograms colors
The program assigns a color to each component box in a histogram
automatically such that equivalent data values maintain a consistent
color wherever they appear in the rows or columns of the histogram.
The colors are taken from successive linetypes, starting either with
the next unused linetype or an initial linetype provided in a
`newhistogram` element.
In some cases this mechanism fails due to data sources that are not
truly parallel (i.e. some files contain incomplete data). In other
cases there may be additional properties of the data that could be
visualized by, say, varying the intensity or saturation of their base
color. As an alternative to the automatic color assignment, you can
provide an explicit color value for each data value in a second `using`
column via the `linecolor variable` or `rgb variable` mechanism.
See `colorspec`. Depending on the layout of your data, the color category
might correspond to a row header or a column header or a data column.
Note that you will probably have to customize the key sample colors
to match (see `keyentry`).
Example: Suppose file_001.dat through file_008.dat contain one column with
a category identifier A, B, C, ... and a second column with a data value.
Not all of the files contain a line for every category, so they are not
truly parallel. The program would be wrong to assign the same color to the
value from line N in each file. Instead we assign a color based on the
category in column 1.
file(i) = sprintf("file_%03d.dat",i)
array Category = ["A", "B", "C", "D", "E", "F"]
color(c) = index(Category, strcol(c))
set style data histogram
plot for [i=1:8] file(i) using 2:(color(1)) linecolor variable
A more complete example including generation of a custom key is in the
demo collection
^
histogram_colors.dem
^
D histogram_colors 1
2 hsteps
?plotting styles hsteps
?style hsteps
?with hsteps
?hsteps
The 2D plotting style `with hsteps` renders a horizontal line segment ("step")
for each data point. The step may extend to the left, to the right, or to
both sides of the point's x-coordinate.
Additional keywords control the lines connecting adjacent steps and option
area fill between the step and a baseline y value.
Syntax:
plot with hsteps
{forward|backward}
{baseline|pillars|link|nolink}
{{above|below} y=}
{offset }
2 columns: x y
3 columns: x y width
This plot style requires 2 or 3 columns of data. Additional input columns can
be used to provide variable line or fill colors (see `rgbcolor variable`).
The x values of the input data are assumed to be monotonic.
If the width of each step is not explicitly given through a third input
column, each segment’s width is calculated so that it abuts the adjacent
horizontal segments. A negative value in column 3 will be treated as a
request for a full-width step.
The `forward` and `backward` keywords can be used to specify the direction
in which the horizontal segment extends from the given x coordinate.
If neither is specified, the horizontal segment extends on both sides
of the given x-value halfway to the x-value of the next adjacent point.
However, for the first and last points, where there are no corresponding outer
adjacent points, the horizontal segments are extrapolated using distances to
the adjacent inner points (see `histeps`, `boxes`).
The default (`baseline`) and `pillar` variants employ a baseline y value.
If not provided in the plot command, the baseline is taken to be y=0.
If the plot command uses a fill style, the baseline also serves to
delimit one boundary of the fill area.
Four style variants are possible.
Ffigure_hsteps_baseline
`baseline` (default): If there is no gap along x between adjacent steps,
they are connected by a vertical line segment between them. This produces
a curve like the `steps`, `histeps`, or `fsteps` styles. If there is a gap
between steps, usually because the width is less than the point spacing,
the connecting line drops to the baseline and continues along it before
rising again. This produces a sequence of rectangular pulses.
set xzeroaxis
plot $data using 1:2 with hsteps
plot $data using 1:2:(0.5) with hsteps
Ffigure_hsteps_pillar
`pillar`: At each end of each step a vertical line is drawn to the baseline.
Note that no horizontal line segments are drawn at the baseline.
plot $data using 1:2 with hsteps pillar
plot $data using 1:2:(0.5) with hsteps pillar
plot $data using 1:2:(0.5) \
with hsteps pillar above fc "blue", \
$data using 1:2:(0.5) \
with hsteps pillar below fc "red"
#TeX \vspace{6ex}
Ffigure_hsteps_nolink
`nolink`: No connecting line is drawn between adjacent steps.
Baseline and fill properties are not relevant to this variant.
plot $data using 1:2 with hsteps nolink, \
$data using 1:2 with hsteps nolink forward, \
$data using 1:2 with hsteps nolink backward, \
$data using 1:2 with points pt "|"
#TeX \vspace{9ex}
Ffigure_hsteps_link
`link`: Adjacent steps steps are connected by a single straight line segment.
Depending on the step widths, this line may be diagonal rather than vertical.
Example: The `link` variant can be superimposed onto the `pillar` variant to
produce a stacked histogram plot in which category boundaries are connected.
set style line 11 lw 2 lc "gray" dt "."
set style line 12 lw 2 lc variable
plot $data using 1:3:(0.5) ls 11 with hsteps link, \
$data using 1:3:(0.5):1 ls 12 with hsteps pillar fs solid 0.7 border, \
$data using 1:4:(0.5) ls 11 with hsteps link, \
$data using 1:4:(0.5):1 ls 12 with hsteps pillar fs transparent pattern 1 border
3 offset
Ffigure_hsteps_offset
?with hsteps offset
?hsteps offset
The offset value modifies any of the `with hsteps` variants by adding an
increment to the y value of both the data point itself (column 2) and the
baseline of the plot it appears in. An example of use is to draw a logic
circuit timing chart in which pulse waveforms are aligned vertically.
In general the offset can be used to stack plots from multiple data sets
that share a common range of y values.
# bit(k,char) is a function that returns 0 or 1
# for the state of bit k in an ASCII character
set style fill solid 0.2 border
plot for [k=1:8] STR using 1:(bit(k,STR[$1])):(0.5) \
with hsteps fillcolor "black" offset k
3 missing data
?with hsteps missing-data
?hsteps missing-data
In the hsteps style, empty lines, NaN values, and missing data have distinct
meanings. If an empty line is present in the data, the data series is reset
at that point. This is analogous to a blank line causing a break to start a
new curve in the case of `with lines`. If an x-value contains NaN, it is
processed in the same manner as an empty line. If the x-value is valid but
the y-value contains NaN, no horizontal line is drawn for that particular data
point but the x-value is still used if needed to estimate the step width.
2 image
?plotting styles image
?style image
?with 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.
These plot styles are often used to produce heatmaps.
For 2D heatmaps in polar coordinates, see `set polar grid`.
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. See also `sparse`.
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
parallelepiped in the plot. The coordinates of each data point will determine
the center of the parallelepiped. 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`.
=alpha channel
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`.
If only a single data column is provided for the color components of either
rgbimage or rgbalpha plots, it is interpreted as containing 32 bit packed ARGB
data using the convention that alpha=0 means opaque and alpha=255 means fully
transparent. Note that this is backwards from the alpha convention if alpha
is supplied in a separate column, but matches the ARGB packing convention for
individual commands to set color. See `colorspec`.
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.
D argb_hexdata 2
3 image pixels
?plotting styles image pixels
?style image pixels
?with image pixels
?image pixels
?pixels
=heatmaps
Some terminals use device- or library-specific optimizations to render image
data within a rectangular 2D area. This sometimes produces undesirable output,
e.g. inter-pixel smoothing, bad clipping or missing edges. An example of this
is the smoothing applied by web browsers when rendering svg images.
The `pixels` keyword tells gnuplot to use generic code to render the image
pixel-by-pixel. This rendering mode is slower and may result in larger output
files, but should produce a consistent rendered view on all terminals.
It may in particular be preferable for heatmaps with a small number of pixels.
Example:
plot 'data' with image pixels
2 impulses
?plotting styles impulses
?style impulses
?with 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
?with 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
?with 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 `linetypes`, `linewidth`, and `linestyle`.
2 linespoints
?plotting styles linespoints
?style linespoints
?with linespoints
?style lp
?with 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 masking
?plotting styles mask
?plot with mask
?with mask
?masking
The plotting style `with mask` is used to define a masking region that
can be applied to pm3d surfaces or to images specified later in the same
`plot` or `splot` command. Input data is interpreted as a stream of [x,y]
or [x,y,z] coordinates defining the vertices of one or more polygons.
As in plotting style `with polygons`, polygons are separated by a blank line.
If the mask is part of a 3D (splot) command then a column of z values is
required on input but is currently not used for anything.
If a mask definition is present in the plot command, then any subsequent image
or pm3d surface in the same command can be masked by adding the keyword `mask`.
If no mask has been defined, this keyword is ignored.
This example illustrates using the convex hull circumscribing a set of points
to mask the corresponding region of a pm3d surface.
Ffigure_mask
^
^
^
^
set table $HULL
plot $POINTS using 1:2 convexhull
unset table
set view map
set multiplot layout 1,2
splot $POINTS using 1:2:3 with pm3d, \
$POINTS using 1:2:(0) nogrid with points
splot $HULL using 1:2:(0) with mask, \
$POINTS using 1:2:3 mask with pm3d
unset multiplot
The `splot` command for the first panel renders the unmasked surface created by
dgrid3d from the original points and then the points themselves, in that order.
The `splot` command for the second panel renders the masked surface. Note that
definition of the mask must come first (plot `with mask`), followed by the pm3d
surface it applies to (plot style `with pm3d` modified by the `mask` keyword).
A more complete version of this example is in the demo collection
^
mask_pm3d.dem
^
Although it is not shown here, a single mask can include multiple polygonal
regions.
The masking commands are EXPERIMENTAL. Details may change in a future release.
2 parallelaxes
Ffigure_parallel
?plotting styles parallelaxes
?plot with parallelaxes
?with parallelaxes
?parallelaxes
?parallel
Parallel axis plots can highlight correlation in a multidimensional data set.
Individual columns of input data are each associated with a separately scaled
vertical axis. If all columns are drawn from a single file then each line on
the plot represents values from a single row of data in that file.
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.
Syntax:
set style data parallelaxes
plot $DATA using col1{:varcol1} {at } {, 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`.
?polar heatmap
Polar heatmaps can be generated using plot style `with surface` together with
`set polar grid`.
Ffigure_polar_grid
set size square
set angle degrees
set rtics
set grid polar
set palette cubehelix negative gamma 0.8
set polar grid gauss kdensity scale 35
set polar grid theta [0:190]
plot DATA with surface, DATA with points pt 7
2 points
?plotting styles points
?style points
?with 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 all points. The point type
defaults to that of the linetype. See `linetypes`. If no `using` spec is found
in the plot command, input data columns are interpreted implicitly in the order
x y pointsize pointtype color
Any columns beyond the first two (x and y) are optional; they correspond to
additional plot properties `pointsize variable`, `pointtype variable`, etc.
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. You may use any unicode
character as the pointtype (assumes utf8 support). See `escape sequences`.
Longer strings may be plotted using plot style `labels` rather than `points`.
plot f(x) with points pt "#"
plot d(x) with points pt "\U+2299"
?points variable
?with points variable
=variable
?variable
?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. See `colorspec`. 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 polygons
?plotting styles polygons
?style polygons
?with polygons
?polygons
2D plots:
plot DATA {using 1:2} with polygons
`plot with polygons` is currently treated as `plot with filledcurves closed`.
Each polygon may be assigned a separate color by providing a third using
specifier and the keywords `lc variable` (value is interpreted as a linetype)
or `lc rgb variable` (value is interpreted as a 24-bit RGB color).
Only the color value from the first vertex of the polygon is used.
The border line type, if any, is taken from the fill style.
3D plots:
splot DATA {using x:y:z} with polygons
{fillstyle }
{fillcolor }
`splot with polygons` uses pm3d to render individual triangles, quadrangles,
and larger polygons in 3D. These may be facets of a 3D surface or isolated
shapes. The code assumes that the vertices lie in a plane.
Vertices defining individual polygons are read from successive records of the
input file. A blank line separates one polygon from the next.
The fill style and color may be specified in the splot command, otherwise the
global fillstyle from `set style fill` is used. Due to limitations in the
pm3d code, a single border line style from `set pm3d border` is applied to all
3D polygons. This restriction may be removed in a later gnuplot version.
Each polygon may be assigned a separate RGB color by providing a fourth using
specifier and the keywords `lc variable` (value is interpreted as a linetype)
or `lc rgb variable` (value is interpreted as a 24-bit RGB color).
Only the color value from the first vertex of the polygon is used.
pm3d sort order and lighting are applied to the faces. It is probably always
desirable to use `set pm3d depthorder`.
Ffigure_polygons
set xyplane at 0
set view equal xyz
unset border
unset tics
set pm3d depth
set pm3d border lc "black" lw 1.5
splot 'icosahedron.dat' with polygons \
fs transparent solid 0.8 fc bgnd
2 rgbalpha
?plotting styles rgbalpha
?style rgbalpha
?with rgbalpha
See `image`.
2 rgbimage
?plotting styles rgbimage
?style rgbimage
?with rgbimage
See `image`.
2 sectors
?plotting styles sectors
?with sectors
?sectors
?windrose
Ffigure_sector_definition
The 2D plotting style `with sectors` renders one annular segment ("sector")
for each line of input data. The shape of each sector is described by four
required data values. An additional pair of data values can be included to
specify the origin of the annulus this sector is taken from.
A per-sector color may be provided in an additional column.
The plot style itself can be used in either cartesian or polar mode
(`set polar`). The units and interpretation for the azimuth and the
sector angle are controlled using `set angles` and `set theta`.
Columns 1 and 2 specify the azimuth (theta) and radius (r) of one corner
of the sector.
#TeX \newline
Columns 3 and 4 specify the angular and radial extents of the sector
("sector_angle" and "annular_width").
#TeX \newline
Columns 5 and 6, if present, specify the coordinates of the center of the
annulus (default [0,0]). The interpretation is [x,y] in cartesian mode
and [theta,r] in polar mode.
Syntax:
plot DATA {using specifier} {units xy | units xx | units yy}
using specifier
4 columns: azimuth radius sector_angle annular_width
5 columns: azimuth radius sector_angle annular_width color
6 columnd: azimuth radius sector_angle annular_width center_x center_y
7 columns: azimuth radius sector_angle annular_width center_x center_y color
Note that if the x and y axis scales are not equal, the envelope of the full
annulus in x/y coordinates will appear as an ellipse rather than a circle.
The annulus envelope and thus the apparent sector annular width can be adjusted
to correct for unequal axis scales using the same mechanism as for ellipses.
Adding `units xx` to the command line causes the sector to be rendered as if
the current x axis scale applied equally to both x and y.
Similarly `units yy` causes the sector to be rendered as if the current
y axis scale applied equally to both x and y.
See `set isotropic`, `set style ellipse`.
Ffigure_windrose
Plotting with sectors can provide polar coordinate equivalents for the
cartesian plot styles `boxes` (see wind rose figure), `boxxyerror` and
`image pixels` (see example in `heatmaps`). Because sector plots are
compatible with cartesian mode plot layout, multiple plots can be placed
at different places on a single graph, which would not be possible for
other polar mode plot styles.
An example of using sectors to create a wind rose in shown here.
Other applications include polar heatmaps, dial charts, pie/donut charts,
and annular error boxes for data points in polar coordinates.
Worked examples for all of these are given in the
^
sectors demo.
^
2 spiderplot
?plotting styles spiderplot
?with spiderplot
?spiderplot
?radar chart
Spider plots are essentially parallel axis plots in which the axes are arranged
radially rather than vertically. Such plots are sometimes called `radar charts`.
In gnuplot this requires working within a coordinate system established by the
command `set spiderplot`, analogous to `set polar` except that the angular
coordinate is determined implicitly by the parallel axis number. The appearance,
labelling, and tic placement of the axes is controlled by `set paxis`.
Further style choices are controlled using `set style spiderplot`, `set grid`,
and the individual components of the plot command.
Because each spider plot corresponds to a row of data rather than a column,
it would make no sense to generate key entry titles in the normal way.
Instead, if a plot component contains a title the text is used to label the
corresponding axis. This overrides any previous `set paxis n label "Foo"`.
To place a title in the key, you can either use a separate `keyentry` command
or extract text from a column in the input file with the `key(column)`
using specifier. See `keyentry`, `using key`.
In this figure a spiderplot with 5 axes is used to compare multiple entities
that are each characterized by five scores. Each line (row) in $DATA
generates a new polygon on the plot.
Ffigure_spiderplot
$DATA << EOD
A B C D E F
George 15 75 20 43 90 50
Harriet 40 40 40 60 30 50
EOD
set spiderplot
set style spiderplot fs transparent solid 0.2 border
set for [p=1:5] paxis p range [0:100]
set for [p=2:5] paxis p tics format ""
set paxis 1 tics font ",9"
set for [p=1:5] paxis p label sprintf("Score %d",p)
set grid spiderplot
plot for [i=1:5] $DATA using i:key(1)
3 newspiderplot
?newspiderplot
?spiderplot newspiderplot
Normally the sequential elements of a plot command `with spiderplot` each
correspond to one vertex of a single polygon. In order to describe multiple
polygons in the same plot command, they must be separated by `newspiderplot`.
Example:
# One polygon with 10 vertices
plot for [i=1:5] 'A' using i, for [j=1:5] 'B' using j
# Two polygons with 5 vertices
plot for [i=1:5] 'A' using i, newspiderplot, for [j=1:5] 'B' using j
2 steps
?plotting styles steps
?style steps
?with 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 surface
?plotting styles surface
?style surface
?with surface
The plot style `with surface` has two uses.
In 3D plots, `with surface` always produces a surface.
If a 3D data set is recognizable as a mesh (grid) then by default the program
implicitly treats the plot style `with lines` as requesting a gridded surface,
making `with lines` a synonym for `with surface`. However the command
`set surface explicit` suppresses this treatment, in which case `with surface`
and `with lines` become distinct styles that may be used in the same plot.
If you have points in 3D that are not recognized as a grid, you may be able
to fit a suitable grid first. See `set dgrid3d`.
In 2D polar mode plots, `with surface` is used to produce a solid fill gridded
represention of the data. Generation of the surface is controlled using the
command `set polar grid`.
2 vectors
?plotting styles vectors
?style vectors
?with 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 inline arrow style properties,
by reference to a predefined arrow style, or by a request to read the index
of the desired arrow style for each vector from a separate input column.
See the first three examples below.
Examples:
plot ... using 1:2:3:4 with vectors filled heads
plot ... using 1:2:3:4 with vectors arrowstyle 3
plot ... using 1:2:3:4:5 with vectors arrowstyle variable
splot 'file.dat' using 1:2:3:(1):(1):(1) with vectors filled head lw 2
Notes: You cannot mix the `arrowstyle` keyword with other line style
qualifiers in the plot command. An additional column of color values is
required if the arrow style includes `lc variable` or `lc rgb variable`.
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`.
See also the 2D plot style `with arrows` that is identical to `with vectors`
except that each arrow is specified using x:y:length:angle.
#TeX \newpage
2 xerrorbars
?plotting styles xerrorbars
?style xerrorbars
?with 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 clearance between the point and the error bars is controlled by
`set pointintervalbox`.
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 variable color.
This style does not permit variable point properties.
2 xyerrorbars
?plotting styles xyerrorbars
?style xyerrorbars
?with 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`. The clearance between the point and the error bars is
controlled by `set pointintervalbox`.
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` specifier of 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 color.
This style does not permit variable point properties.
#TeX \newpage
2 xerrorlines
?plotting styles xerrorlines
?style xerrorlines
?with 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 variable color.
This style does not permit variable point properties.
2 xyerrorlines
?plotting styles xyerrorlines
?style xyerrorlines
?with 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` specifier of 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 color.
This style does not permit variable point properties.
2 yerrorbars
?plotting styles yerrorbars
?plotting styles errorbars
?style yerrorbars
?with yerrorbars
?style errorbars
?with errorbars
?yerrorbars
=errorbars
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`. The clearance between the point and the error bars is
controlled by `set pointintervalbox`.
2 columns: [implicit x] y ydelta
3 columns: x y ydelta
4 columns: x y ylow yhigh
Additional input columns may be used to provide information such as variable
point size, point type, or color.
See also
^
errorbar demo.
^
2 yerrorlines
?plotting styles yerrorlines
?plotting styles errorlines
?style yerrorlines
?with yerrorlines
?style errorlines
?with errorlines
?yerrorlines
?errorlines
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
Additional input columns may be used to provide information such as variable
point size, point type, or color.
See also
^
errorbar demo.
^
#TeX \newpage
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. See `hidden3d`.
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`.
3 2D projection (set view map)
?2D projection (set view map)
Ffigure_mapcontours
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 onto the xy plane.
See `set view map`. This plot mode is useful for contour plots and heat maps.
This figure shows contours plotted once with plot style `lines` and once with
style `labels`.
3 PM3D plots
?PM3D PLOTS
Ffigure_pm3dsolid
3D surfaces can also be drawn using solid pm3d quadrangles rather than
lines. In this case there is no hidden surface removal, but if the component
facets are drawn back-to-front then a similar effect is achieved.
See `set pm3d depthorder`. While pm3d surfaces are by default colored using a
smooth color palette (see `set palette`), it is also possible to specify a
solid color surface or to specify distinct solid colors for the top and bottom
surfaces as in the figure shown here. See `pm3d fillcolor`.
Unlike the line-trimming in hidden3d mode, pm3d surfaces can be smoothly
clipped to the current zrange. See `set pm3d clipping`.
#TeX \newpage
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)
2 isosurface
?plotting styles isosurface
?style isosurface
?with isosurface
?isosurface
Ffigure_isosurface
This 3D plot style requires a populated voxel grid (see `set vgrid`, `vfill`).
Linear interpolation of voxel grid values is used to estimate fractional grid
coordinates corresponding to the requested isolevel. These points are then
used to generate a tessellated surface. The facets making up the surface are
rendered as pm3d polygons, so the surface coloring, transparency, and border
properties are controlled by `set pm3d`. In general the surface is easier to
interpret visually if facets are given a thin border that is darker than the
fill color. By default the tessellation uses a mixture of quadrangles and
triangles. To use triangle only, see `set isosurface`.
Example:
set style fill solid 0.3
set pm3d depthorder border lc "blue" lw 0.2
splot $helix with isosurface level 10 fc "cyan"
2 Zerrorfill
?plotting styles zerrorfill
?style zerrorfill
?with 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
Ffigure_zerror
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 `set pm3d depthorder base`.
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 Animation
?animation
Any of gnuplot's interactive terminals (qt win wxt x11 aqua) can be used
to display an animation by plotting successive frames from the command line
or from a script.
Several non-mousing terminals also support some form of animation.
See `term sixelgd`, `term kittycairo`.
Two terminals can save an animation to a file for later playback locally
or by embedding it a web page. See `term gif animate`, `term webp`.
^
^
^
^
^
Example:
unset border; unset tics; unset key; set view equal xyz
set pm3d border linecolor "black"
set term webp animate delay 50
set output 'spinning_d20.webp'
do for [ang=1:360:2] {
set view 60, ang
splot 'icosahedron.dat' with polygons fc "gold"
}
unset output
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" ...
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 ARG1 ... ARG9 are stored in ordinary string variables
they may be dereferenced by macro expansion. However in many cases it is
more natural to use them as you would any other variable.
In parallel with the string representation of parameters ARG1 ... ARG9,
the parameters themselves are stored in an array ARGV[9]. See `ARGV`.
DEPRECATED: Versions prior to 5.0 performed macro-like substitution of the
special tokens $0, $1, ... $9 with the literal contents of ...
That older mechanism is no longer supported.
EXPERIMENTAL: Function blocks (new in this version) provide a more flexible
alternative to `call`. See `function blocks`.
3 ARGV[ ]
?argv
?ARGV
?call argv
?call ARGV
When a gnuplot script is entered via the `call` command any parameters passed
by the caller are available via two mechanisms. Each parameter is stored as a
string in variables ARG1, ARG2, ... ARG9. Each parameter is also stored as one
element of the array ARGV[9]. Numerical values are stored as complex variables.
All other values are stored as strings. ARGC holds the number of parameters.
Thus after a call
call 'routine_1.gp' 1 pi "title"
The three arguments are available inside routine_1.gp as follows
ARGC = 3
ARG1 = "1" ARGV[1] = 1.0
ARG2 = "3.14159" ARGV[2] = 3.14159265358979...
ARG3 = "title" ARGV[3] = "title"
In this example ARGV[1] and ARGV[2] have the full precision of a floating point
variable. ARG2 lost precision in being stored as a string using format "%g".
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 because ARG1 is a string it 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"
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 gnuplot commands contained in a string
or in a function block. Newline characters are not allowed within the string.
evaluate "commands in a string constant"
evaluate string_valued_function( ... arguments ... )
evaluate $functionblock( ... arguments ... )
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 `function blocks` and `substitution macros` for other mechanisms
that construct or execute strings containing gnuplot commands.
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 where a set of
measured x and y values read from a file are used to be modeled by a
function y = f(x).
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. In this case 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 the weighted sum of
squared residuals (WSSR), for which the residuals are weighted by the input
data errors 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 the user-defined function will be a sum of simple
functions, not involving any parameters, each multiplied by one parameter.
Nonlinear least-squares 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 the linear special case
is also solved along with more general nonlinear 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
?statistical_overview
The theory of non-linear least-squares 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 `fit 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 a nonlinear least-squares 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 practical_guidelines
?fit 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 nonlinear least-squares 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
=FIT_LOG
=FIT_SCRIPT
There are two environment variables that can be defined to affect `fit`.
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. The default is to write "fit.log" in the current working directory.
This can be overwritten at run time 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 can be changed at run time using `set fit script`.
For many other run time adjustments to way fit works, see `set fit`.
3 error recovery
?commands fit error_recovery
?fit error_recovery
Starting with gnuplot version 6, the `fit` command always returns to the
next command input line regardless of the success or failure of fitting.
This allows scripted recovery from fit errors. The variable FIT_ERROR is
set to 0 on success, non-zero on error. This example plots however many
of five data sets can be successfully fit. Failure for data set 2 would
not prevent fitting data sets 3 through 5.
do for [i=1:5] {
DATA = sprintf("Data_%05d.dat", i)
fit f(x) DATA via a,b,c
if (FIT_ERROR || !FIT_CONVERGED) {
print "Fit failed for ", DATA
continue
}
set output sprintf("dataset_%05.png", i)
plot DATA, f(x)
unset output
}
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 time data
?commands fit time_data
?fit time_data
In fitting time data it is important to remember that gnuplot represents
time as seconds since 1 January 1970. For example if you wanted to fit a
quadratic model for the time dependence of something measured over the course
of one day in 2023, you might expect that it could be done using
T(x) = a + b*x + c*x*x
set xdata time
fit T(x) 'hits.dat' using 1:3 via a,b,c
This will probably fail, because internally the x values corresponding to
that one day will have a range something like [1.67746e+09 : 1.67754e+09].
The fractional change in x across the measured data will be only about
1.e-05 and to guarantee convergence you would probably need many
decimal places of accuracy in the initial parameter estimates.
One solution is to recast the problem as change in time since the start
of measurement.
set xdata time # data format "27-02-2023 12:00:00 measurement"
timefmt = "%d-%m-%Y %H:%M:%S"
set timefmt timefmt
t0 = strptime( timefmt, "27-02-2023 00:00:00" )
fit T(x) 'temperature.dat' using ($1-t0):3 via a,b,c
This shifts the range of the data to [0 : 86400], which is more tractable.
Another possibility in this case is to ignore the date in column 1 and use
relative time formats (tH/tM/tS) applied to column 2.
set timefmt "%tH:%tM:%tS"
fit T(x) 'temperature.dat' using 2:3 via a,b,c
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!"
#TeX \newpage
2 function blocks
?commands function
?function blocks
?functionblocks
The `function` command signals the definition of a here-document containing
a named block of gnuplot code that can be called as a function.
As with data blocks, the name of a function block must begin with a '$'.
Up to nine named parameters may be specified as part of the definition.
These names may be used inside the function block as local variables.
See `local` and `scope`.
Once the function block is defined, you can invoke it by name anywhere that
a normal function could be used. If the return value is not relevant, the
function block may be invoked by an "evaluate" command rather than as part
of an assignment expression.
Example:
function $sinc(arg) << EOF
if (arg == 0) { return 1.0 }
return sin(arg) / arg
EOF
gnuplot> plot $sinc(x) with lines title "sinc(x) as a function block"
It is not necessary to specify a list of named arguments to a function block
at the time it is declared. Arguments to the function passed from the command
line can be also be accessed from inside the function block as ARGV[1] etc,
as they would be for a `call` command. See `ARGV`. This allows defining a
function block that can operate on a variable number of arguments.
Example:
function $max << EOF
local max = real("-Inf")
if (ARGC == 0) { return NaN }
do for [i=1:ARGC] {
if (max < ARGV[i]) {
max = ARGV[i]
}
}
return max
EOF
gnuplot> foo = $max( f(A), 2.0, C, Array[3] )
gnuplot> baz = $max( foo, 100. )
The primary motivation for function block support is to allow definition of
complicated functions directly in gnuplot. Execution is of course slower
than if the same function were coded in C or Fortran, but this is acceptable
for many purposes. If execution speed matters then the function can be
implemented later as a plugin instead (see `plugins`).
A second use for function blocks is to allow execution of gnuplot commands in
a context they otherwise could not appear. Suppose for example you want to
plot data from two csv files, but one file uses comma-separated fields while
the other uses semicolon-separated fields. Normally this property would have
been set by a previous `set datafile` command and would have to match all
files used by the plot command. However we can define a function block to
invoke as a definition immediately before each file is referenced in the plot.
function $set_csv(char) << EOF
set datafile separator char
EOF
plot tmp=$set_csv(",") FILE1, tmp=$set_csv(";") FILE2
Limitations:
#start
#b Data blocks and function blocks cannot be defined inside a function block.
#b These commands cannot be executed inside a function block:
## `reset`, `shell`, `!`.
#b A `plot`, `replot`, `splot`, `refresh`, `stats`, `vfill`, or `fit` command
## is accepted in a function block only if none of those commands is already
## in progress. E.g. you cannot use `stats` in a function block called by a
## `plot` command, you cannot invoke `plot` from inside a `fit` command, etc.
#end
A non-trivial example of using function blocks to implement and plot
a 15-term Lanczos approximation for the complex lngamma function is
provided in the demo collection as
^
function_block.dem
^
The function block implementation is slower by a factor of roughly 25 compared
to the built-in lnGamma function using the same algorithm coded directly in C.
Nevertheless it is still fast enough for 3D interactive rotation.
#TeX The function definitions used in that demo are show below.
#TeX \newline
#TeX \begin{center}
#TeX \begin{minipage}{5in}
#TeX {
#TeX Function block implementation of $log\Gamma(z)$ using a 15-term Lanczos approximation
#TeX \hrule
#TeX ~\newline
#TeX \small
#TeX \begin{verbatim}
#TeX array coef[15] = [ ... ]
#TeX
#TeX function $Lanczos(z) << EOD
#TeX local Sum = coef[1] + sum [k=2:15] coef[k] / (z + k - 1)
#TeX local temp = z + 671./128.
#TeX temp = (z + 0.5) * log(temp) - temp
#TeX temp = temp + log( sqrt(2*pi) * Sum/z )
#TeX return temp
#TeX EOD
#TeX
#TeX function $Reflect(z) << EOD
#TeX local w = $Lanczos(1.0 - z)
#TeX local temp = log( sin(pi * z) )
#TeX return log(pi) - (w + temp)
#TeX EOD
#TeX
#TeX my_lngamma(z) = (z == 0) ? NaN : (real(z) < 0.5) ? $Reflect(z) : $Lanczos(z)
#TeX \end{verbatim}
#TeX \hrule
#TeX }
#TeX \end{minipage}
#TeX \end{center}
Use of function blocks is EXPERIMENTAL.
Details may change before inclusion in a release version.
#TeX \newpage
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 or the location of the saved history file, 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
hist !"set xr" # like above, several words enclosed in quotes
hist !55 # reexecute the command at history entry 55
2 if
?commands if
?if
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.
Prior to gnuplot version 5 the scope of 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.
Old syntax:
if () [; else if () ...; else ...]
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.
2 for
?for
The `plot`, `splot`, `set` and `unset` commands may optionally contain an
iteration 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
=plugins
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. See `plugins`.
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 gnuplot commands can be
executed by a `load` command. Files being loaded may themselves contain
`load` or `call` commands. To pass arguments to a loaded file, see `call`.
Syntax:
load ""
load $datablock
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 systems that support a popen function, 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.
EXPERIMENTAL: It is also possible to execute commands from lines of text
stored internally. See `function blocks`. A function block may be defined
in-line or in an external file. Once the function block has been defined
the commands may be executed repeatedly using `evaluate` on the internal
copy rather than reloading the file.
2 local
?local
?commands local
Syntax:
local foo =
local array foo[size]
The `local` keyword introduces declaration of a variable whose scope
is limited to the execution of the code block in which it is declared.
Declaration is optional, but without it all variables are global.
If the name of a local variable duplicates the name of a global variable,
the global variable is shadowed until exit from the local scope.
See `scope`.
Local declarations may be used to prevent a global variable from being
unintentionally overwritten by a `call` or `load` statement. They are
particularly useful inside a function block. The `local` command is also
valid inside the code block in curly brackets following an `if`, `else`,
`do for`, or `while` statement.
Example: Suppose you want to write a script "plot_all_data.gp" containing
commands that plot a bunch of data sets. You want to call this convenience
script from the command line or from other scripts without worrying that it
trashes any variables with names "file" or "files" or "dataset" or "outfile".
The variable "file" is inherently local because it is an iteration variable
(see `scope`) but the other three names need keyword `local` to protect them.
plot_all_data.gp:
local files = system("ls -1 *.dat")
do for [file in files] {
local dataset = file[1:strstrt(file,".dat")-1]
local outfile = dataset . ".png"
set output outfile
plot file with lines title dataset
}
unset output
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