Manual
This manual covers all aspects of using Gaston.
Configuration
The terminal
By default, gnuplot chooses an appropriate terminal: qt
or wxt
on Linux, windows
on Windows, and aqua
on MacOS. The terminal can be set by changing the value of Gaston.config.term
; for example:
= "pngcairo font ',10' size 700,400"; Gaston.config.term
To show the terminals supported by gnuplot, run:
terminals() Gaston.
Other settings
Gaston.config.output
: controls how plots are displayed. Possible values are::external
: plots are displayed in GUI windows. This is the default value.:echo
: sends text-based plots (likepng
andsixelgd
) back to the terminal. Useful for notebooks and IDEs, and for plotting on the terminal.:null
: execute all plot commands but do not actually produce a plot.
pngcairo
andconfig.output
to:echo
. When the automatic detection does not work, these setting have to be set manually.Gaston.config.embedhtml
:Bool
, defaults tofalse
. Enables embedding plots in HTML; useful to enable interactivity in Pluto and Jupyter notebooks.
Location of gnuplot executable
If gnuplot is not in the system’s path, its location can be set using the environmental variable JULIA_GNUPLOT_EXE
. This variable must be set before Gaston is loaded.
Plotting
The plot
function is used to plot one curve, while plot!
is used to add a curve to the same plot. 3-D plots are created with splot
and splot!
. plot
returns a value of type Figure
, which contains a vector of Axis
(each containing one or more Plot
s, or curves.
A plot
command takes four different kinds of arguments: a figure (possibly indexed), settings, data, and plotline, in that order.
plot([figure,] [settings...,] data..., [plotline...])
Further curves may be added using plot!
. (For 3-D plots, use splot
and splot!
instead.)
More specifically, a plot
command takes:
- Optionally, a figure where the plot is to be produced.
- If the figure is indexed, then the plot will be produced in the specified axis (if it doesn’t exist, it will be created).
- Zero or more settings arguments, which get converted to gnuplot
set
commands. - One or more data arguments, which are written to a file in the format gnuplot expects.
- Zero or more plotline arguments, which are appended to gnuplot’s
plot
orsplot
commands.
Gaston provides several alternative ways to specify settings and plotlines.
Settings and Plotlines
All the following are equivalent.
- One single string
plot("set grid
unset key'A Sinusoid'",
set title
x, y,"with linespoints lc 'green'")
- Multiple strings
plot("set grid", "unset key \n set title 'A Sinusoid'",
x, y,"with linespoints", "lc 'green'")
- Keywords with
@plot
@plot({grid = true, key = false, title = "'A Sinusoid'"},
x, y,= "linespoints", lc = "'green'"}) {with
- Keywords with
@gpkw
:
@gpkw plot({grid = true, key = false, title = "'A Sinusoid'"},
x, y,= "linespoints", lc = "'green'"}) {with
Keyword options are enclosed in curly brackets {}
. To set an option without arguments, such as set grid
, use either a lone grid
, or grid = true
. To unset an option, such as in unset grid
, use grid = false
. Options can be repeated; each one will be converted to a separate set
line.
@plot
also accepts strings, and in fact strings and keywords may be combined:
@plot({grid, key = false}, "set title 'A Sinusoid'",
x, y,"with linespoints", {lc = "'green'"})
It is possible to omit the parenthesis, but in this case the command must fit in a single line.
@plot {grid, key = false, title = "'A Sinusoid'"} x y {with = "lp", lc = "'green'"}
For 3-D plots, use the macro @splot
.
Quoted strings
All strings passed to gnuplot must be enclosed in single quotes, such as in lc = "'green'"
in the example above. The @Q_str
string macro can help reduce the number of quotes needed:
@plot {grid = true, key = false, title = Q"A Sinusoid"} x y {with = "lp", lc = Q"green"}
This macro turns "abc"
into "'abc'"
.
Keyword parsing
Some @plot
(or @gpkw
) keyword arguments are parsed by Gaston, providing syntax that may be more convenient than gnuplot’s. The following list is for keywords that specify axis settings:
- For any keyword argument,
{arg}
or{arg = true}
is parsed toset arg
, while{arg = false}
is parsed tounset arg
. - For
xtics
,ytics
,ztics
ortics
:{tics = R}
whereR
is anAbstractRange
is parsed asset tics $(first(R)), $(step(R)), $(last(R))
.{tics = T}
whereT
is aTuple
is parsed asset tics $T
.{tics = NT}
whereNT
is aNamedTuple
is parsed as in this example:{tics = (labels = ("one", "two"), positions = (0, 2))}
is equivalent toset tics ('one' 0, 'two' 2, )
- For
xrange
,yrange
,zrange
,cbrange
:{xrange = R}
whereR
is a vector or tuple is parsed asset xrange [$R[1]:$R[2]]
- If
R
contains anInf
, then it is replaced with*
.
- If the keyword is
ranges
, then all four ranges listed above are set. - For
palette
, if the value is a symbol, then the corresponding color scheme fromColorSchemes.jl
is converted to gnuplot’s format. If a tuple of two symbols is provided and the second one is:reverse
, then the order of the palette is reversed. - For
{view = V}
, ifV
is aTuple
, then it is parsed asset view $V[1], $V[2]
. - For
{linetype = S}
whereS
is aSymbol
, then the corresponding color scheme is converted to a set of line types, one per color in the scheme. - For
{margins = T}
whereT
is aTuple
is parsed as in this example:{margins = (1, 2, 3, 4)}
is equivalent toset lmargin at screen 1
,set rmargin at screen 2
,set bmargin at screen 3
,set tmargin at screen 4
.
The following list is for keywords that specify plotline elements:
plotstyle
is equivalent towith
.markersize
andms
are equivalent topointsize
.legend
is equivalent totitle
.marker
is equivalentpointtype
.
In addition, marker
, pointtype
and pt
accept symbolic names for the marker types, according to the following table:
name | gnuplot pointtype |
---|---|
:dot | 0 |
:⋅ | 0 |
:+ | 1 |
:plus | 1 |
:x | 2 |
:* | 3 |
:star | 3 |
:esquare | 4 |
:fsquare | 5 |
:ecircle | 6 |
:fcircle | 7 |
:etrianup | 8 |
:ftrianup | 9 |
:etriandn | 10 |
:ftriandn | 11 |
:edmd | 12 |
:fdmd | 13 |
Data
Data to be plotted can be provided as vectors and/or matrices. Gaston converts the data to a format compatible with gnuplot. Three cases are supported: * All data arguments are vectors. * The first two arguments are vectors of length n
and m
, and the third argument is a matrix of size n x m
; further arguments are optional. * All provided arguments are matrices of size n x m
.
Recipes
Recipes can be provided to convert arbitrary types to data that gnuplot understands.
Functions
Functions can be plotted directly, with a given range and number of samples, which can be specified in the following alternative ways:
# g is a function
plot(g) # plots `g` evaluated at 100 samples, from -10 to 9.99
plot((a, b), g) # plots `g` evaluated at 100 samples, from a to b
plot((a, b, c), g) # plots `g` evaluated at c samples, from a to b
plot(x, g) # plots g.(x)
Plot with table
In some cases, it is useful to have gnuplot produce plot data in a “table” format, which can then be plotted. See an example in contour lines on heatmap. The (non-exported) function Gaston.plotwithtable
returns a Gaston.DataTable
storing the table. All plot commands accept this type.
The following DataTable
constructors are provided:
DataTable(vs::Vector{<:AbstractString}...)
DataTable(ts::T) where T <: Tuple
; the tuple is assumed to contain strings.DataTable(args::Matrix...)
; each matrix is a datablock.
Simple themes
Frequently-used settings or plotlines may be stored in a “theme”; the @gpkw
macro processes keyword arguments wrapped in curly brackets.
= @gpkw {grid, key = false}
theme plot(theme, x, y)
Themes may be combined with other themes and/or with strings:
= @gpkw {xlabel = Q"X"}
theme2 plot(theme, "set title 'A Sinusoid'", theme2, x, y)
Themes can also be used for plotlines, and these may also be combined with other themes and/or strings.
= @gpkw {w = "lp", pt = "'o'", ps = 3}
pltheme plot(theme, "set title 'A Sinusoid'", theme2, x, y, pltheme)
Gaston includes a few generic themes:
Axis themes | Description |
---|---|
:notics | Removes all tics |
:labels | Generic axis labels (x , y , z ) |
:nocb | Removes colorbox |
:unitranges | Set all ranges to [-1:1] |
For example, the following command plots a sine wave with no tics and generic x
and y
axis labels:
plot(:notics, :labels, "set title 'Example'", (-1, 1), sin)
Themes are also used to provide common plot types (illustrated in Themes). The following are the provided specialized plot commands and the themes they use:
Command | Settings theme | Plotline theme |
---|---|---|
scatter , scatter! |
:scatter , :scatter3 |
:scatter |
stem , stem! |
None | :stem , :impulses (optional) |
bar , bar! |
:boxplot |
:box |
barerror , barerror! |
:boxerror |
:box |
histogram |
:histplot |
:box , :horhist (1-D); :image (2-D) |
imagesc |
:imagesc |
:image , :rgbimage |
surf , surf! |
:hidden3d |
:pm3d |
contour |
:contour |
:labels (optional) |
surfcontour |
:contourproj |
:labels (optional) |
wireframe , wireframe! |
:hidden3d |
None |
wiresurf , wiresurf! |
:wiresurf |
None |
heatmap |
:heatmap |
:pm3d |
Plotline themes must be handled with care: gnuplot requires plotline
options to be specified in a certain order, which may not be repeated, and
some combinations are invalid. It is very easy to create erroneous
plotlines.
Gaston does not validate that the settings and plotline given to gnuplot are valid. When gnuplot returns an error or warning, it is echoed to the terminal.
Multiplot
As mentioned above, a Figure
contains a vector of Axis
. Any figure with more than one axis is plotted using gnuplot’s multiplot
feature (except in the case where the terminal configuration contains animate
).
There are several ways to insert axes into a figure. The first is to index into the figure:
= Figure()
f plot(f[2], sin)
plot(f[4], cos)
Note that:
- Indexing into a non-existing axis creates an empty axis at that index.
- It’s possible to have empty axes (
f[1]
andf[3]
above are empty). - By default, Gaston will manage the figure’s layout, trying to keep a square aspect ratio. In the example above, the figure will have dimensions 2x2.
The second method is to push!
a figure into another:
= plot(sin)
f1 = plot(cos)
f2 push!(f1, f2)
Here, the axis at f[2]
will be inserted into the axes vector of f1
. It is possible to index into a figure to obtain a specific axis:
= plot(sin)
f1 plot(f1[2], cos) # f1 now contains two axes
= Figure()
f2 plot(tan) # plot goes into f2 since it is the active figure
push!(f2, f1[2]) # the axis with a plot of cos is inserted into f2
The third and final method is to plot multiple figures together:
plot(f1, f2, multiplot = "...", autolayout = ...)
This will return a new figure with all axes from f1
and f2
. Any number of figures may be provided as arguments.
The Figure
constructor takes a couple of options to control how multiplot behaves:
multiplot
: a string that is appended toset multiplot
, such as"title 'A multiplot'"
. Defaults to""
.autolayout
: a boolean that controls whether Gaston should manage the figure’s layout. Defaults totrue
.
Managing multiple figures
Gaston has the ability to create and manage multiple GUI plot windows simultaneously. Each window is backed up by its own gnuplot process. The following commands can be used to create and control multiple windows.
Creating and selecting figures
Figure()
Creates a new, empty figure. All figures are of type Gaston.Figure
. Gaston keeps internal references to all figures, to prevent them from being garbage collected. As described above, Figure
takes two optional arguments, multiplot
and autolayout
.
When a figure is created, it becomes the active figure, meaning that subsequent plot commands will go to this figure by default. It is possible to keep figures in different variables:
= Figure()
fig1 = Figure() fig2
and then redirect plot commands to the desired figure:
plot(fig1, ...) # plot goes to fig1
plot!(fig2, ...) # new curve added to fig2
By default, plot
resets the contents of a figure.
Usually it is more convenient to keep figures in variables, but it is also possible to manage figures using handles:
Figure("density") # figure with handle "density"
Figure(:volume) # figure with handle :volume
Figure(33) # figure with handle 33
Handles can be of any type. All figures have a handle. By default, handles are integers in increasing order starting from 1.
The keyword argument handle
allows specifying the destination of a plot
command:
plot(..., handle = :volume)
plot!(..., handle = 33)
scatter(..., handle = "density")
To activate a figure given its handle, use:
figure(handle)
It is possible to make an existing figure f
the active figure with:
figure(f)
With no arguments, figure()
returns the current figure.
To obtain the list of all current figures and their handles, and to identify the active figure, use the unexported function Gaston.listfigures()
.
Closing figures
To close the active figure, run
closefigure()
The figure with handle h
can be closed with closefigure(h)
. Likewise, to close figure f
use closefigure(f)
. Closing a figure quits the underlying gnuplot process.
To close all figures, use closeall()
.
Saving plots
A plot can be saved to a file in any format supported by gnuplot, with the function
save([f] ; filename, term)
where the arguments are:
f
, which can be either aFigure
, or an arbitrary value that is taken to be the handle of the figure to save. Defaults to the active figure.filename
, a string that specifies the filename. If empty, it defaults tofigure-
followed by the figure’s handle; the filename extension is set to the first three characters of the gnuplot terminal (see next argument).term
, specifies the gnuplot terminal used to save the plot; defaults to"pngcairo font ',7'"
.
Defining new plot types and recipes
There are several ways to extend Gaston to create new plot types or to plot arbitrary types. One is to define a new function that returns a Gaston.Figure
. The rest involve extending Gaston.convert_args
in various ways.
Functions that return a Gaston.Figure
The first way to extend Gaston to handle arbitrary types is to define a new function (and optionally new themes) that returns a Gaston.Figure
. See an example here. For 3-D plot commands such as splot
, the function convert_args3
should be used instead.
The recommended way to proceed is to:
- Define new themes if necessary, by adding key-value pairs to
Gaston.sthemes
and/orGaston.pthemes
. - Process the function arguments as required.
- Create a new figure inside the function, using either
Figure
orMultiFigure
. - Use
plot
to add new axes and curves to the figure, possibly using the new themes. - Return the figure.
Adding new methods to Gaston.convert_args
When the data provided to plot
is not of a type that gnuplot directly understands, Gaston calls the function convert_args
, defined in the package GastonRecipes
. This function returns a value of one of three different types:
GastonRecipes.PlotRecipe
, used to define a single curve (coordinates and a plotline). See and example here.GastonRecipes.AxisRecipe
, used to define an axis (settings, a vector ofPlotRecipe
s, and a boolean to define if the axis is three dimensional). See an example here.GastonRecipes.FigureRecipe
, used to define a full figure (a vector ofAxisRecipes
, plus multiplot and autolayout settings). See an example here.
The function convert_args
is called with all data and all keyword arguments given to the plot
command. Keyword arguments can be used to control the recipe’s behavior.
Note that these functions and types are not exported by Gaston.
Internals
In Gaston, the basic building block is the Plot
type. This type has two fields: the plotline, a string; and the name of a file where the coordinates are stored. When a Plot
is constructed, the data provided is immediately written to a file; a Plot
does not store any coordinates.
On top of Plot
we have the Axis
type, which contains a vector of Plot
s, a string with the axis settings, and a boolean that indicates whether the axis should be rendered with plot
(2-D) or splot
(3-D).
Finally, on top of Axis
we have the Figure
type, which contains a vector of Axis
plus multiplot configuration. Besides, a Figure
contains a figure handle, and most importantly, a gnuplot process with which it communicates. Each figure is associated with a different gnuplot process.
When a Figure
is displayed by Julia, the show
function builds a set of commands that are sent to gnuplot. Gnuplot is instructed to send a sentinel string back to the figure, which indicates that gnuplot is done displaying the figure (and also prevents race conditions).
Each Figure
is associated with a finalizer that makes sure its associated gnuplot process exits gracefully.
Gaston uses the following functions to set up and communicate with gnuplot:
gp_start
initializes a new gnuplot process and connects to its stdin, stdout and stderr streams.gp_quit
terminates a gnuplot process.gp_send
sends a string of commands to an existing gnuplot process.gp_exec
starts a new gnuplot process, sends it commands, and quits the process.
Gaston also keeps some internal state:
Gaston.state.figures
stores pointers to all existing figures.Gaston.state.enabled
istrue
if gnuplot is runnable.Gaston.state.activefig
stores the handle of the currently active figure.