API
Index
Gnuplot.Dataset
Gnuplot.DatasetBin
Gnuplot.DatasetText
Gnuplot.IsoContourLines
Gnuplot.Options
Gnuplot.Path2d
Gnuplot.GnuplotProcess.gpexec
Gnuplot.GnuplotProcess.gpvars
Gnuplot.GnuplotProcess.quit
Gnuplot.GnuplotProcess.terminal
Gnuplot.GnuplotProcess.terminals
Gnuplot.boxxy
Gnuplot.contourlines
Gnuplot.dgrid3d
Gnuplot.gpmargins
Gnuplot.gpranges
Gnuplot.gpversion
Gnuplot.hist
Gnuplot.hist_bins
Gnuplot.hist_weights
Gnuplot.line
Gnuplot.linetypes
Gnuplot.palette
Gnuplot.palette_levels
Gnuplot.palette_names
Gnuplot.parseKeywords
Gnuplot.parseSpecs
Gnuplot.quitall
Gnuplot.repl_init
Gnuplot.save
Gnuplot.savescript
Gnuplot.session_names
Gnuplot.show_specs
Gnuplot.stats
Gnuplot.tcm
Gnuplot.test_terminal
Gnuplot.v2argb
Gnuplot.version
Gnuplot.@gp
Gnuplot.@gsp
Exported symbols
The list of Gnuplot.jl exported symbols is as follows:
Gnuplot.@gp
— Macro@gp args...
The @gp
macro, and its companion @gsp
for 3D plots, are used to add plot specs to a session and optionally update a plot. It accepts all arguments accepted by Gnuplot.parseSpecs
and Gnuplot.parseKeywords
, plus the following optional ones:
a leading literal
:-
: avoids resetting the session before adding new plot specs;a literal symbol (as first argument, or immediately after the
:-
symbol): name of the gnuplot session to address. If not given the default session is used;a trailing literal
:-
: avoids immediately updating the plot.
The leading and trailing :-
symbols are used to add specs to a gnuplot session using multiple statements rather than a single one.
Example:
# Reset default session and generate new plot
@gp [-1,1] [-1,1] "w l t 'Main diagonal'" [-1,1] [1,-1] "w l t 'Antidiagonal'" [0] [0] "w p t 'Origin'"
# Break above statement in three separate ones, and address the :foo session:
@gp :foo [-1,1] [-1,1] "w l t 'Main diagonal'" :- # reset :foo session, do not update the plot
@gp :- :foo [-1,1] [1,-1] "w l t 'Antidiagonal'" :- # add spec to the :foo session, do not update the plot
@gp :- :foo [0] [0] "w p t 'Origin'" # add spec to the :foo session, update the plot
Gnuplot.@gsp
— Macro@gsp args...
This macro accepts the same syntax as @gp
, but produces a 3D plot instead of a 2D one.
Gnuplot.boxxy
— Functionboxxy(x, y; xmin=NaN, ymin=NaN, xmax=NaN, ymax=NaN, cartesian=false)
boxxy(h::StatsBase.Histogram)
Gnuplot.contourlines
— Functioncontourlines(x, y, z, cntrparam="level auto 4")
contourlines(x, y, z, fractions)
contourlines(h::StatsBase.Histogram, ...)
Compute paths of contour lines for 2D data, and return a vector of IsoContourLines
object.
This feature is not available in dry mode and will raise an error if used.
Arguments:
x
,y
(asAbstractVector{Float64}
): Coordinates;z::AbstractMatrix{Float64}
: the levels on which iso-contour lines are to be calculated;cntrparam::String
: settings to compute contour line paths (see gnuplot documentation forcntrparam
);fractions::Vector{Float64}
: compute contour lines encompassing these fractions of total counts;h::StatsBase.Histogram
: use 2D histogram bins and counts to compute contour lines.
Example
x = randn(10^5);
y = randn(10^5);
h = hist(x, y, nbins1=20, nbins2=20);
clines = contourlines(h, "levels discrete 500, 1500, 2500");
# Use implicit recipe
@gp clines
# ...or use IsoContourLines fields:
@gp "set size ratio -1"
for i in 1:length(clines)
@gp :- clines[i].data "w l t '$(clines[i].z)' lw $i dt $i"
end
# Calculate probability within 0 < r < σ
p(σ) = round(1 - exp(-(σ^2) / 2), sigdigits=3)
# Draw contour lines at 1, 2 and 3 σ
clines = contourlines(h, p.(1:3));
@gp palette(:beach, smooth=true, rev=true) "set grid front" "set size ratio -1" h clines
Gnuplot.dgrid3d
— Functiondgrid3d(x, y, z, opts=""; extra=true)
Interpolate non-uniformly spaced 2D data onto a regular grid.
This feature is not available in dry mode and will raise an error if used.
Arguments:
x
,y
,z
(asAbstractVector{Float64}
): coordinates and values of the function to interpolate;opts
: interpolation settings (see gnuplot documentation fordgrid3d
);extra
: iftrue
(default) compute inerpolated values in all regions, even those which are poorly constrained by input data (namely, extrapolated values). Iffalse
set these values toNaN
.
Return values:
A tuple with x
and y
coordinates on the regular grid (as Vector{Float64}
), and z
containing interpolated values (as Matrix{Float64}
).
Example
x = (rand(200) .- 0.5) .* 3;
y = (rand(200) .- 0.5) .* 3;
z = exp.(-(x.^2 .+ y.^2));
# Interpolate on a 20x30 regular grid with splines
gx, gy, gz = dgrid3d(x, y, z, "20,30 splines")
@gsp "set size ratio -1" "set xyplane at 0" xlab="X" ylab="Y" :-
@gsp :- x y z "w p t 'Scattered data' lc pal"
@gsp :- gx gy gz "w l t 'Interpolation on a grid' lc pal"
The splines
algorithm may be very slow on large datasets. An alternative option is to use a smoothing kernel, such as gauss
:
x = randn(2000) .* 0.5;
y = randn(2000) .* 0.5;
rsq = x.^2 + y.^2;
z = exp.(-rsq) .* sin.(y) .* cos.(2 * rsq);
@gsp "set size ratio -1" palette(:balance, smooth=true) "set view map" "set pm3d" :-
@gsp :- "set multiplot layout 1,3" xr=[-2,2] yr=[-2,2] :-
@gsp :- 1 tit="Scattered data" x y z "w p notit lc pal"
# Show extrapolated values
gx, gy, gz = dgrid3d(x, y, z, "40,40 gauss 0.1,0.1")
@gsp :- 2 tit="Interpolation on a grid\\n(extrapolated values are shown)" gx gy gz "w l notit lc pal"
# Hide exrapolated values
gx, gy, gz = dgrid3d(x, y, z, "40,40 gauss 0.1,0.1", extra=false)
@gsp :- 3 tit="Interpolation on a grid\\n(extrapolated values are hidden)" gx gy gz "w l notit lc pal"
Gnuplot.GnuplotProcess.gpexec
— Functiongpexec(sid::Symbol, command::String)
gpexec(command::String)
Execute the gnuplot command command
on the underlying gnuplot process of the sid
session, and return the results as a String
. If a gnuplot error arises it is propagated as an ErrorException
.
If the sid
argument is not provided, the default session is considered.
Examples:
gpexec("print GPVAL_TERM")
gpexec("plot sin(x)")
Gnuplot.gpmargins
— Functiongpmargins(sid::Symbol)
gpmargins()
Return a NamedTuple
with keys l
, r
, b
and t
containing respectively the left, rigth, bottom and top margins of the current plot (in screen coordinates).
Gnuplot.gpranges
— Functiongpranges(sid::Symbol)
gpranges()
Return a NamedTuple
with keys x
, y
, z
and cb
containing respectively the current plot ranges for the X, Y, Z and color box axis.
Gnuplot.GnuplotProcess.gpvars
— Functiongpvars(sid::Symbol, filter="all")
gpvars(filter="all")
Return a NamedTuple
with all currently defined gnuplot variables, as returned by show var $filter
. If the sid
argument is not provided, the default session is considered.
Gnuplot.hist
— Functionhist(v::Vector{T}; range=extrema(v), bs=NaN, nbins=0) where T <: Real
Calculates the histogram of the values in v
.
Arguments
v
: a vector of values to compute the histogra;range
: values of the left edge of the first bin and of the right edge of the last bin;bs
: size of histogram bins;nbins
: number of bins in the histogram;
If nbins
is given bs
is ignored. Internally, hist
invokes StatsBase.fit(Histogram...)
and returns the same data type (see here). The only difference is that hist
also accounts for entries on outer edges so that the sum of histogram counts is equal to the length of input vector. As a consequence, the closed=
keyword is no longer meaningful. Consider the following example:
julia> using StatsBase
julia> v = collect(1:5);
julia> h1 = fit(Histogram, v, 1:5, closed=:left)
julia> h2 = hist(v, range=[1,5], bs=1)
julia> print(h1.weights)
[1, 1, 1, 1]
julia> print(h2.weights)
[1, 1, 1, 2]
julia> @assert length(v) == sum(h1.weights) # this raises an error!
julia> @assert length(v) == sum(h2.weights) # this is fine!
Example
v = randn(1000)
h = hist(v, range=[-3.5, 3.5], bs=0.5)
@gp h # preview
# Custom appearence
@gp hist_bins(h) hist_weights(h) "w steps t 'Histogram' lw 3"
@gp :- hist_bins(h) hist_weights(h) "w fillsteps t 'Shaded histogram'" "set style fill transparent solid 0.5"
@gp :- hist_bins(h) hist_weights(h) "w lp t 'side=:left' lw 3"
@gp :- hist_bins(h, side=:center) hist_weights(h) "w lp t 'side=:center' lw 3"
@gp :- hist_bins(h, side=:right) hist_weights(h) "w lp t 'side=:right' lw 3"
hist(v1::Vector{T1 <: Real}, v2::Vector{T2 <: Real}; range1=[NaN,NaN], bs1=NaN, nbins1=0, range2=[NaN,NaN], bs2=NaN, nbins2=0)
Calculates the 2D histogram of the values in v1
and v2
.
Arguments
v1
: a vector of values along the first dimension;v2
: a vector of values along the second dimension;range1
: values of the left edge of the first bin and of the right edge of the last bin, along the first dimension;range1
: values of the left edge of the first bin and of the right edge of the last bin, along the second dimension;bs1
: size of histogram bins along the first dimension;bs2
: size of histogram bins along the second dimension;nbins1
: number of bins along the first dimension;nbins2
: number of bins along the second dimension;
If nbins1
(nbins2
) is given bs1
(bs2
) is ignored. Internally, hist
invokes StatsBase.fit(Histogram...)
and returns the same data type (see here). See help for hist
in 1D for a discussion on the differences.
Example
v1 = randn(1000)
v2 = randn(1000)
h = hist(v1, v2, bs1=0.5, bs2=0.5)
@gp h # preview
@gp "set size ratio -1" "set autoscale fix" hist_bins(h, 1) hist_bins(h, 2) hist_weights(h) "w image notit"
Gnuplot.hist_bins
— Functionhist_bins(h::StatsBase.Histogram{T <: Real, 1, R}; side=:left, pad=true)
Returns the coordinates of the bins for a 1D histogram.
Note: the returned coordinates depend on value of the side
keyword:
side=:left
(default): coordinates are returned for the left sides of each bin;side=:center
: coordinates are returned for the center of each bin;side=:right
: coordinates are returned for the right sides of each bin;
If the pad
keyword is true
two extra bins are added at the beginning and at the end.
hist_bins(h::StatsBase.Histogram{T <: Real, 2, R}, axis)
Returns the coordinates of the bins for a 2D histogram along the specified axis.
Note: unlike 1D case, the returned coordinate are always located in the center of the bins.
Gnuplot.hist_weights
— Functionhist_weights(h::StatsBase.Histogram{T <: Real, 1, R}; pad=true)
hist_weights(h::StatsBase.Histogram{T <: Real, 2, R})
Returns the weights of each bin in a histogram.
Note: in the 1D case, if the pad
keyword is true
two extra bins with zero counts are added at the beginning and at the end.
Gnuplot.line
— Functionline(scalar_x, vector_y, spec)
line(vector_x, scalar_y, spec)
Explicit recipe to plot a line parallel to one axis.
Example:
@gp line(randn(100), 0.5, "w l t 'Parallel to X'")
@gp :- line(0.5, randn(100), "w l t 'Parallel to Y' dt 2")
Gnuplot.linetypes
— Functionlinetypes(cmap::ColorScheme; lw=1, ps=1, dashed=false, rev=false)
linetypes(s::Symbol; lw=1, ps=1, dashed=false, rev=false)
Convert a ColorScheme
object into a string containing the gnuplot commands to set up linetype colors.
If the argument is a Symbol
it is interpreted as the name of one of the predefined schemes in ColorSchemes.
If rev=true
the line colors are reversed. If a numeric or string value is provided through the lw
and ps
keywords thay are used to set the line width and the point size respectively. If dashed
is true the linetypes with index greater than 1 will be displayed with dashed pattern.
Gnuplot.palette
— Functionpalette(cmap::ColorScheme; rev=false, smooth=false)
palette(s::Symbol; rev=false, smooth=false)
Convert a ColorScheme
object into a string containing the gnuplot commands to set up the corresponding palette.
If the argument is a Symbol
it is interpreted as the name of one of the predefined schemes in ColorSchemes.
If rev=true
the palette is reversed. If smooth=true
the palette is interpolated in 256 levels.
Gnuplot.palette_levels
— Functionpalette_levels(cmap::ColorScheme; rev=false, smooth=false)
palette_levels(s::Symbol; rev=false, smooth=false)
Convert a ColorScheme
object into a Tuple{Vector{Float64}, Vector{String}, Int}
containing:
- the numeric levels (between 0 and 1 included) corresponding to colors in the palette;
- the corresponding colors (as hex strings);
- the total number of different colors in the palette.
If the argument is a Symbol
it is interpreted as the name of one of the predefined schemes in ColorSchemes.
If rev=true
the palette is reversed. If smooth=true
the palette is interpolated in 256 levels.
Gnuplot.palette_names
— Functionpalette_names()
Return a vector with all available color schemes for the palette
and linetypes
function.
Gnuplot.session_names
— Functionsession_names()
Return a vector with all currently active sessions.
Gnuplot.show_specs
— Functionshow_specs(sid::Symbol)
show_specs()
Prints a brief overview of all stored plot specs for the sid
session. If sid
is not provided the default session is considered.
Gnuplot.stats
— Functionstats(sid::Symbol)
stats()
Print a statistical summary all datasets belonging to sid
session. If sid
is not provided the default session is considered.
This function is actually a wrapper for the gnuplot command stats
.
Gnuplot.tcm
— Functiontcm(palette::Symbol; alpha::Union{Real, Function}=0.5, kwargs...)
Defines a Transparent Color Map (TCM) based on the given palette name. The alpha=
keyword allows to specify a transparency level in the range 0 (opaque) to 1 (transparent), or to provide a mapping function accepting a single float number in the range 0:1, and returning a float in the same range. Any further keyword is forwarded to palette()
.
Example
x = rand(500);
@gp "set multiplot layout 1,2"
@gp :- 1 tcm(:hawaii, alpha=0.5) x "u 0:1:1 notit w p pt 7 lc pal tcm"
@gp :- 2 tcm(:hawaii, alpha=x -> sqrt(x)) x "u 0:1:1 notit w p pt 7 lc pal tcm"
Gnuplot.GnuplotProcess.terminals
— Functionterminals()
Return a Vector{String}
with the names of all the available gnuplot terminals.
Gnuplot.GnuplotProcess.terminal
— Functionterminal(sid::Symbol)
terminal()
Return a String
with the current gnuplot terminal (and its options) of the process associated to session sid
, or to the default session (if sid
is not provided).
Gnuplot.test_terminal
— Functiontest_terminal(term=nothing; linetypes=nothing, palette=nothing)
Run the test
and test palette
commands on a gnuplot terminal.
If no term
is given it will use the default terminal. If lt
and pal
are given they are used as input to the linetypes
and palette
function repsetcively to load the associated color scheme.
Examples
test_terminal()
test_terminal("wxt", lt=:rust, pal=:viridis)
Gnuplot.v2argb
— Functionv2argb(v::Vector{<: Real}; kwargs...)
v2argb(palette::Symbol, v::Vector{<: Real};
range=extrema(v),
alpha::Union{Real, Function, Nothing}=nothing,
kwargs...)
Map a vector of numbers within the range range
into a corresponding vector of Ints
representing (A)RGB colors using the specified palette and transparency settings. The latter is supposed to be used with the colorspec "lc rgb var". Transparency can be specified via the alpha=
keyword, either as a constant transparency level in the range 0 (opaque) to 1 (transparent), or by providing a mapping function accepting a single float number in the range 0:1, and returning a float in the same range. Any further keyword is forwarded to palette()
.
Example
Plot points from a 2D Gaussian distribution using colors and transparencies depending on the distance from the origin.
using Random
x = randn(500);
y = randn(500);
dist = sqrt.(x.^2 + y.^2)
@gp "set size ratio -1" :-
@gp :- x y v2argb(:brg, dist, alpha=x -> sqrt(x)) "w p notit lc rgb var"
Non-exported symbols
The following functions are not exported by the Gnuplot.jl package since they are typically not used in every day work, or aimed to debugging purposes. Still, they can be useful in some case, hence they are documented here.
In order to call these functions you should add the Gnuplot.
prefix to the function name.
Gnuplot.Dataset
— TypeDataset
Abstract type for all dataset structures.
Gnuplot.DatasetText
— TypeDatasetText
A dataset whose data are stored as a text buffer.
Transmission to gnuplot may be slow for large datasets, but no temporary file is involved, and the dataset can be saved directly into a gnuplot script. Also, the constructor allows to build more flexible datasets (i.e. mixing arrays with different dimensions).
Constructors are defined as follows:
DatasetText(data::Vector{String})
DatasetText(data::Vararg{AbstractArray, N}) where N
In the second form the type of elements of each array must be one of Real
, AbstractString
and Missing
.
Gnuplot.DatasetBin
— TypeDatasetBin
A dataset whose data are stored as a binary file.
Ensure best performances for large datasets, but involve use of a temporary file. When saving a script the file is stored in a directory with the same name as the main script file.
Constructors are defined as follows:
DatasetBin(cols::Vararg{AbstractMatrix, N}) where N
DatasetBin(cols::Vararg{AbstractVector, N}) where N
In both cases the element of the arrays must be a numeric type.
Gnuplot.IsoContourLines
— TypeIsoContourLines
Coordinates of all contour lines of a given level.
Fields
paths::Vector{Path2d}
: vector ofPath2d
objects, one for each continuous path;data::Vector{String}
: vector with string representation of all paths (ready to be sent to gnuplot);z::Float64
: level of the contour lines.
Gnuplot.Options
— TypeOptions
Structure containing the package global options, accessible through Gnuplot.options
.
Fields
dry::Bool
: whether to use dry sessions, i.e. without an underlying Gnuplot process (default:false
)cmd::String
: command to start the Gnuplot process (default:"gnuplot"
)default::Symbol
: default session name (default::default
)term::String
: default terminal for interactive use (default: empty string);gpviewer::Bool
: use a gnuplot terminal as main plotting device (iftrue
) or an external viewer (iffalse
);init::Vector{String}
: commands to initialize the session when it is created or reset (e.g., to set default palette);verbose::Bool
: verbosity flag (default:false
)preferred_format::Symbol
: preferred format to send data to gnuplot. Value must be one of:bin
: fastest solution for large datasets, but uses temporary files;text
: may be slow for large datasets, but no temporary file is involved;auto
(default) use a heuristic to identify the best strategy.
Gnuplot.Path2d
— TypePath2d
A path in 2D.
Fields
x::Vector{Float64}
y::Vector{Float64}
Gnuplot.gpversion
— FunctionGnuplot.gpversion()
Return the gnuplot application version.
Raise an error if version is < 5.0 (required to use data blocks).
Gnuplot.GnuplotProcess.quit
— FunctionGnuplot.quit(sid::Symbol)
Quit the session identified by sid
and the associated gnuplot process (if any).
Gnuplot.quitall
— FunctionGnuplot.quitall()
Quit all the sessions and the associated gnuplot processes.
Gnuplot.parseKeywords
— FunctionparseKeywords(; kws...)
Parse keywords and return corresponding gnuplot commands. The accepted keywords are:
xrange=[low, high]
=>"set xrange [low:high]
;yrange=[low, high]
=>"set yrange [low:high]
;zrange=[low, high]
=>"set zrange [low:high]
;cbrange=[low, high]
=>"set cbrange[low:high]
;key="..."
=>"set key ..."
;title="..."
=>"set title "...""
;xlabel="..."
=>"set xlabel "...""
;ylabel="..."
=>"set ylabel "...""
;zlabel="..."
=>"set zlabel "...""
;cblabel="..."
=>"set cblabel "...""
;xlog=true
=>set logscale x
;ylog=true
=>set logscale y
;zlog=true
=>set logscale z
.cblog=true
=>set logscale cb
;margins=...
=>set margins ...
;lmargin=...
=>set lmargin ...
;rmargin=...
=>set rmargin ...
;bmargin=...
=>set bmargin ...
;tmargin=...
=>set tmargin ...
;
All Keyword names can be abbreviated as long as the resulting name is unambiguous. E.g. you can use xr=[1,10]
in place of xrange=[1,10]
.
Gnuplot.parseSpecs
— FunctionparseSpecs(args...; kws...)
Parse plot spec and convert them in a form suitable to be sent to the underlying gnuplot process. The function accepts any number of arguments, with the following meaning:
a leading
Int
(>= 1) is interpreted as the plot destination in a multi-plot session;one, or a group of consecutive, array(s) of either
Real
orString
build up a dataset. The different arrays are accessible as columns 1, 2, etc. from thegnuplot
process. The number of required input arrays depends on the chosen plot style (seegnuplot
documentation);a string occurring before a dataset is interpreted as a
gnuplot
command (e.g.set grid
). If the string begins with "plot" or "splot" it is interpreted as the corresponding gnuplot commands (note: "plot" and "splot" can be abbreviated to "p" and "s" respectively, or "pl" and "spl", etc.);a string occurring immediately after a dataset is interpreted as a plot element for the dataset, by which you can specify
using
clause,with
clause, line styles, etc.. All keywords may be abbreviated following gnuplot conventions.an input in the form
"\$name"=>(array1, array2, etc...)
is interpreted as a named dataset. Note that the dataset name must always start with a "$
";any object
<:AbstractGPSpec
orVector{<:AbstractGPSpec}
is simply appended to the output.any other data type is processed through an implicit recipe. If a suitable recipe do not exists an error is raised.
All keywords will be processed via the Gnuplot.parseKeywords
function.
Gnuplot.repl_init
— FunctionGnuplot.init_repl(; start_key='>')
Install a hook to replace the common Julia REPL with a gnuplot one. The key to start the REPL is the one provided in start_key
(default: >
).
Note: the gnuplot REPL operates only on the default session.
Gnuplot.save
— Functionsave([sid::Symbol,] filename:String; term="")
Export a plot into filename
using the terminal provided via the term=
keyword.
If the sid
argument is provided the operation applies to the corresponding session, otherwise the default session is considered.
Example:
@gp hist(randn(1000))
Gnuplot.save("output.png", term="pngcairo")
Gnuplot.savescript
— Functionsavescript([sid::Symbol,] filename::String)
Save a gnuplot script in filename
, to be used in a separate gnuplot session (Julia is no longer needed) to generate exactly the same plot.
If the sid
argument is provided the operation applies to the corresponding session, otherwise the default session is considered.
Example:
@gp hist(randn(1000))
Gnuplot.savescript("my_script.gp")
Gnuplot.version
— FunctionGnuplot.version()
Return the Gnuplot.jl package version.