API

API

Index

Exported symbols

The list of Gnuplot.jl exported symbols is as follows:

Gnuplot.@gpMacro.
@gp args...

The @gp macro, and its companion @gsp for 3D plots, allows to send data and commands to the gnuplot using an extremely concise syntax. The macros accepts any number of arguments, with the following meaning:

  • one, or a group of consecutive, array(s) of either Real or String build up a dataset. The different arrays are accessible as columns 1, 2, etc. from the gnuplot process. The number of required input arrays depends on the chosen plot style (see gnuplot documentation);

  • a string occurring before a dataset is interpreted as a gnuplot command (e.g. set grid);

  • 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. Moreover, "plot" and "splot" can be abbreviated to "p" and "s" respectively;

  • the special symbol :- allows to split one long statement into multiple (shorter) ones. If given as first argument it avoids starting a new plot. If it given as last argument it avoids immediately running all commands to create the final plot;

  • any other symbol is interpreted as a session ID;

  • an Int (>= 1) is interpreted as the plot destination in a multi-plot session (this specification applies to subsequent arguments, not previous ones);

  • 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 "$";

  • an input in the form keyword=value is interpreted as a keyword/value pair. The accepted keywords and their corresponding gnuplot commands are as follows:

    • 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].

  • a PlotElement object is expanded in its fields and processed as one of the previous arguments;

  • any other data type is processed through an implicit recipe. If a suitable recipe do not exists an error is raised.

Gnuplot.@gspMacro.
@gsp args...

This macro accepts the same syntax as @gp, but produces a 3D plot instead of a 2D one.

Gnuplot.boxxyFunction.
boxxy(x, y; xmin=NaN, ymin=NaN, xmax=NaN, ymax=NaN, cartesian=false)
boxxy(h::Histogram2D)
Gnuplot.contourlinesFunction.
contourlines(x, y, z, cntrparam="level auto 4")
contourlines(x, y, z, fractions)
contourlines(h::Histogram2D, ...)

Compute paths of contour lines for 2D data, and return a vector of IsoContourLines object.

Note

This feature is not available in dry mode and will raise an error if used.

Arguments:

  • x, y (as AbstractVector{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 for cntrparam);
  • fractions::Vector{Float64}: compute contour lines encompassing these fractions of total counts;
  • h::Histogram2D: use 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.dataset_namesFunction.
dataset_names(sid::Symbol)
dataset_names()

Return a vector with all dataset names for the sid session. If sid is not provided the default session is considered.

Gnuplot.dgrid3dFunction.
dgrid3d(x, y, z, opts=""; extra=true)

Interpolate non-uniformly spaced 2D data onto a regular grid.

Note

This feature is not available in dry mode and will raise an error if used.

Arguments:

  • x, y, z (as AbstractVector{Float64}): coordinates and values of the function to interpolate;
  • opts: interpolation settings (see gnuplot documentation for dgrid3d);
  • extra: if true (default) compute inerpolated values in all regions, even those which are poorly constrained by input data (namely, extrapolated values). If false set these values to NaN.

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"
Warn

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.gpexecFunction.
gpexec(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 Vector{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.gpmarginsFunction.
gpmargins(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.gprangesFunction.
gpranges(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.gpvarsFunction.
gpvars(sid::Symbol)
gpvars()

Return a NamedTuple with all currently defined gnuplot variables. If the sid argument is not provided, the default session is considered.

Gnuplot.histFunction.
hist(v::Vector{T}; range=extrema(v), bs=NaN, nbins=0, pad=true) where T <: Real

Calculates the histogram of the values in v and returns a Histogram1D structure.

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;
  • pad: if true add one dummy bins with zero counts before the first bin and after the last.

If bs is given nbins is ignored.

Example

v = randn(1000)
h = hist(v, bs=0.5)
@gp h  # preview
@gp h.bins h.counts "w histep notit"
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 and returns a Histogram2D structure.

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 bs1 (bs2) is given nbins1 (nbins2) is ignored.

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 auto fix" h.bins1 h.bins2 h.counts "w image notit"
Gnuplot.linetypesFunction.
linetypes(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.paletteFunction.
palette(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_namesFunction.
palette_names()

Return a vector with all available color schemes for the palette and linetypes function.

Gnuplot.recipeFunction.
recipe(h::Histogram1D)
recipe(h::Histogram2D)

Implicit recipes to visualize 1D and 2D histograms.

recipe(c::IsoContourLines)
recipe(v::Vector{IsoContourLines})

Implicit recipes to visualize iso-contour lines.

recipe(M::Matrix{ColorTypes.RGB{T}}, opt="flipy")
recipe(M::Matrix{ColorTypes.RGBA{T}}, opt="flipy")
recipe(M::Matrix{ColorTypes.Gray{T}}, opt="flipy")
recipe(M::Matrix{ColorTypes.GrayA{T}}, opt="flipy")

Implicit recipes to show images.

Gnuplot.saveFunction.
save([sid::Symbol]; term="", output="")
save([sid::Symbol,] mime::Type{T}; output="") where T <: MIME
save([sid::Symbol,] script_filename::String, ;term="", output="")

Export a (multi-)plot into the external file name provided in the output= keyword. The gnuplot terminal to use is provided through the term= keyword or the mime argument. In the latter case the proper terminal is set according to the Gnuplot.options.mime dictionary.

If the script_filename argument is provided a gnuplot script will be written in place of the output image. The latter can then be used in a pure gnuplot session (Julia is no longer needed) to generate exactly the same original 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))
save(MIME"text/plain")
save(term="pngcairo", output="output.png")
save("script.gp")
Gnuplot.session_namesFunction.
session_names()

Return a vector with all currently active sessions.

Gnuplot.statsFunction.
stats(sid::Symbol,name::String)
stats(name::String)
stats(sid::Symbol)
stats()

Print a statistical summary for the name dataset, belonging to sid session. If name is not provdied a summary is printed for each dataset in the session. If sid is not provided the default session is considered.

This function is actually a wrapper for the gnuplot command stats.

Gnuplot.terminalsFunction.
terminals()

Return a Vector{String} with the names of all the available gnuplot terminals.

Gnuplot.terminalFunction.
terminal(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_terminalFunction.
test_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)

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.DatasetType.
Dataset

Abstract type for all dataset structures.

DatasetEmpty

An empty dataset.

DatasetText

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.

DatasetBin

A dataset whose data are stored as a binary file.

Ensure best performances for large datasets, but involve use of a temporary files. 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.

Histogram1D

A 1D histogram data.

Fields

  • bins::Vector{Float64}: bin center values;
  • counts::Vector{Float64}: counts in the bins;
  • binsize::Float64: size of each bin;
Histogram2D

A 2D histogram data.

Fields

  • bins1::Vector{Float64}: bin center values along first dimension;
  • bins2::Vector{Float64}: bin center values along second dimension;
  • counts::Vector{Float64}: counts in the bins;
  • binsize1::Float64: size of each bin along first dimension;
  • binsize2::Float64: size of each bin along second dimension;
IsoContourLines

Coordinates of all contour lines of a given level.

Fields

  • paths::Vector{Path2d}: vector of Path2d 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.OptionsType.
Options

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, i.e. use gnuplot settings);
  • mime::Dict{DataType, String}: dictionary of MIME types and corresponding gnuplot terminals. Used to export images with either save() or show() (see Display options);
  • gpviewer::Bool: use a gnuplot terminal as main plotting device (if true) or an external viewer (if false);
  • 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) automatically choose the best strategy.
source
Gnuplot.Path2dType.
Path2d

A path in 2D.

Fields

  • x::Vector{Float64}
  • y::Vector{Float64}
PlotElement

Structure containing element(s) of a plot (commands, data, plot specifications) that can be used directly in @gp and @gsp calls.

Fields

  • mid::Int: multiplot ID (use 0 for single plots);
  • is3d::Bool: true if the data are supposed to be displayed in a 3D plot;
  • cmds::Vector{String}: commands to set plot properties;
  • name::String: name of the dataset (use "" to automatically generate a unique name);
  • data::Dataset: a dataset
  • plot::Vector{String}: plot specifications for the associated Dataset;

The constructor is defined as follows:

PlotElement(;mid::Int=0, is3d::Bool=false,
            cmds::Union{String, Vector{String}}=Vector{String}(),
            name::String="",
            data::Dataset=DatasetEmpty(),
            plot::Union{String, Vector{String}}=Vector{String}(),
            kwargs...)

No field is mandatory, i.e. even Gnuplot.PlotElement() provides a valid structure. The constructor also accept all the keywords accepted by parseKeywords.

Gnuplot.gpversionFunction.
Gnuplot.gpversion()

Return the gnuplot application version.

Raise an error if version is < 5.0 (required to use data blocks).

Gnuplot.quitFunction.
Gnuplot.quit(sid::Symbol)

Quit the session identified by sid and the associated gnuplot process (if any).

Gnuplot.quitallFunction.
Gnuplot.quitall()

Quit all the sessions and the associated gnuplot processes.

Gnuplot.repl_initFunction.
Gnuplot.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.versionFunction.
Gnuplot.version()

Return the Gnuplot.jl package version.