GNUPLOT reference

Gnuplot An Interactive Plotting Program -
http://www.bersch.net/gnuplot-doc/gnuplot.html
Publication quality plots with Gnuplot -
http://triclinic.org/2015/05/publication-quality-plots-with-gnuplot/
Creating Publication-Ready EPS/PDF files from Gnuplot -
https://michaelgoerz.net/notes/creating-publication-ready-eps-pdf-files-from-gnuplot.html

gnuplot in Action Pg.No: 104 Modifiers for the appearance of lines, points
gnuplot in Action Pg.No: 276 Startup and initialization files
gnuplot in Action Pg.No: 216 Font resolution
gnuplot in Action Pg.No: 218 Tabel 10.1 Control characters for enhanced text mode

# startup and initialization files
gnuplot> show loadpath

# loading script.gp in gnuplot
$ cat script.gp | gnuplot

# loading script.gp with data file.dat in gnuplot
$ cat script.gp file.dat | gnuplot

# load script.gp with data file.dat in gnuplot & direct output plot to graph.png
$ cat script.gp file.dat | gnuplot > graph.png

# complete workflow to export to file
gnuplot> plot exp(-x**2)            # plot command
gnuplot> set terminal pngcairo      # selects the file format
gnuplot> set output "graph.png"     # specifies the output filename
gnuplot> replot                     # repeats the most recent plot command
gnuplot> set terminal wxt           # restores the terminal settings
gnuplot> set output                 # sends output to the screen again by using
                                    # an empty filename


# saving and loading commands
gnuplot> save "graph.gp"
gnuplot> load "graph.gp"


# examples of user-defined variables and constants
gnuplot> e = 2.71828182845905           # the base of the natural logarithm
gnuplot> sqrt2 = sqrt(2.0)              # the square root of 2
gnuplot> euler = 0.57721566490153       # the euler-mascheroni constant


# examples of user-defined functions
f(x) = -x * log(x)
gauss(x,m,s) = exp(-0.5 * ((x-m)/s)**2)/sqrt(2*pi*s**2)
binom(n,k) = n!/(k! * (n-k)!)   # uses the factorial operator
min(a,b) = (a < b) ? a : b      # uses the ternary ? operator
step(x) = (x < 0) ? 0 : 1       # a piece-wise defined function
g(x) = exp(-0.5*(x/s)**2)/s
plot s=1 g(x), s=2 g(x), s=3 g(x)
g(x,s) = exp(-0.5*(x/s)**2)/s
plot g(x,1), g(x,2), g(x,3)
f(x) = abs(x) < 1 ? 1 : NaN


# loop over numbers
plot "data" u 1:2 w l, "" u 1:3 w l, "" u 1:4 w l
plot for [j=2:4] "data" u 1:j w l      # obtain the same plot as in the previous


# modifiers for the appearence of lines, plots, and other graph elements
Keyword                 Abbreviation (Ref: gnuplot in Action, Pg.No: 104)
-------------------------------------
linetype                    lt
linestyle                   ls
linewidth                   lw
linecolor                   lc
dashtype                    dt
pointtype                   pt
pointsize                   ps
pointinterval               pi
textcolor                   tc
fillstyle                   fs
fillcolor                   fc
border                      bo
arrowstyle                  as
plot                        pl
splot                       spl
with                        w
with lines                  w l
with points                 w p
with linespoints            w lp
with vectors                w vec
using                       u
line and point              lp
index                       i
every                       ev
smooth                      s
smooth acsplines            s acs
smooth frequency            s f
smooth kdensity             s kdens
title                       t
set output                  set o
set terminal                set t
set logscale                set logsc


# set margin
set margins <left>, <right>, <bottom>, <top>

# plot two functions
gnuplot> pl sin(x) t 'sine', cos(x) t 'cosine'
gnuplot> spl sin(x)*cos(x) t 'sinusoid'

# for information on plotting 3-D data
gnuplot> help splot


gnuplot> show version long
gnuplot> set terminal
gnuplot> show terminal

    terminal type is x11

gnuplot> show samples

    sampling rate is 1000, 1000

gnuplot> set samples 5000
gnuplot> show samples

    sampling rate is 5000, 5000

gnuplot> plot sin(x) ls 2 # line style changes color (prefer: 1,3,6,7,8,9,11)
gnuplot> plot sin(x) lw 4 # line width changes width
gnuplot> plot sin(x) ps 3 # point style changes point

Display terminal styles with test
gnuplot> test

At any point during an interactive gnuplot session you can store the command
used to create the most recent plot to a file with save:
gnuplot> save "filename.gp"

You can run a command file, either for the interactive prompt with load
gnuplot> load 'filename.gp"
Or by running the file directly form the terminal prompt
$ chmod a+x filename.gp
$ ./filename.gp

The default ordinate range is not always good
gnuplot> plot sin(x), x, x-(x**3)/6

Change the default ordinate range:
gnuplot> plot [] [-2:2] sin(x), x, x-(x**3)/6
[] [] - default x and y range value
[] [-2:2] - default x but range value of y is -2:2
gnuplot> set xrange [0:1]
gnuplot> set yrange [-2:2]

Plotting data from a file:
* By default gnuplot expects data to be numeric and whitespace separated.
* If datafile contains multiple columns, use the using directive to specify
  which columns to plot.
* Can plot multiple datasets on the same plot.
gnuplot> plot "filename" using 1:2, "filename" u 1:3
* By default data points from a file are plotted, we can style the data using
  the with directive.
gnuplot> plot "filename" u 1:2 with lines, " " u 1:3 w linespoints/linesp
gnuplot> plot "filename" u 1:2 w l title "XYZ", " " u 1:3 w linesp t "PQR"
gnuplot> set xlabel "xlabel_name"
gnuplot> set ylabel "ylabel_name"
gnuplot> replot     # replot the last command with the new settings

Smooth unique:
The smooth unique commands allows data sorting on the fly
gnuplot> plot "jumbled" w lp
gnuplot> plot "jumbled" smooth unique w lp t "unjumbled"

gnuplot offers other options to interpolate and smooth data
* bezier calculates and plots a Bezier approximation of order n, where n is the
  number of data points
* sbezier applies the unique transformation first then calculates and plots a
  Bezier approximation
* csplines applies the unique transformation first then calculates natural cubic
  splines to the results
* acsplines applies the unique transformation first then forms a weighted cubic
  splines approximation. The weight is taken from a third argument to the using
  directive.

User defined functions:
gnuplot allows the user to define functions and variables for plotting.
gnuplot> g(x) = a*cos(x)/a
gnuplot> plot a=1, g(x), a=2, g(x)

Data transformations:
Arbitrary functions (include user defined functions) can be applied to each data
point of a file.
gnuplot> g(x) = a*cos(x)/a
gnuplot> a = 23
gnuplot> plot "filename" u 1:(g($1+$2))
The column 0 is a psuedocolumn containing the line number of the datafile
gnuplot> plot "filename" using 0:1

Plotting with style:
* gnuplot itself knows very little about rendering the style of the points,
  lines, fill, etc. This is left to the terminal.
* Line and point styles can be changed by explicitly identifying the line/point
  type associated with the terminal.
* Common style directives
  * linestyle (ls)
  * pointstyle (ps)
  * lineweight (lw)
* Display terminal styles with test
gnuplot> test

References: http://idl.utsa.edu/me5013/lessons/   # for pdf slides
* Book: Gnuplot in Action, P.K. Janert
* Gnuplot -not so Frequently Asked Questions
* Official documentation
* Reference Card

# png output
gnuplot> set terminal pngcairo

# pdf output
gnuplot> set terminal pdfcairo

# svg output
gnuplot> set terminal svg

gnuplot: Terminal types and LATEX Integration

gnuplot Terminals:
* The terminal is what actually renders the graphics in gnuplot
* Many different types are available, mainly grouped as follows
  * Standard Graphics Formats - GIF, JPG, PNG, SVG, etc.
  * Graphics for print - PostScript, PDF
  * Interactive terminals - x11, wxt, Aqua, dumb
* To see a full listing, launch gnuplot and type
gnuplot> set terminal
gnuplot> set term dumb
gnuplot> plot sin(x)
gnuplot> set term png
gnuplot> set output "filename.png"
gnuplot> replot
gnuplot> exit()

# plot a sinusoid and cosinus function
gnuplot> a = 0.9
gnuplot> f(x) = a * sin(x)
gnuplot> g(x) = a * cos(x)
gnuplot> plot [-2*pi:2*pi] f(x) title "wave" w l ls 1 g(x) notitle w l ls 2

$ gnuplot -p plotscript.gp
The command line option -p instructs gnuplot to keep the figure on the screen
after finishing plotting.

# postscript terminal
gnuplot> set terminal postscript enhanced color
gnuplot> set output "result.ps"

# plotting each file in a directory
To plot every file in the current directory, either of the following two
commands will work:
gnuplot> files = system("ls")
gnuplot> plot for [f in files] f u 1:2      # uses the system() function
gnuplot> plot for [f in "`ls`"] f u 1:2     # uses backticks

# batch processing
$ gnuplot plot1.gp plot2.gp plot3.gp        # using command-line arguments
$ cat plot1.gp plot2.gp plot3.gp | gnuplot  # reading from standard input
gnuplot> load "plot1.gp"                    # from within a gnuplot session
gnuplot> load "plot2.gp"
gnuplot> load "plot3.gp"

# do loop
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

# the built-in color sequences
[Gnuplot in Action 2nd Edition, Chapter 9. Color, style, and appearance]

set colorsequence [ default | classic | podo ]

The three color schemes are identified using keywords:
    * default   - A terminal-independent sequence of eight colors
    * classic   - The original behavior, which differs from terminal to terminal
                  but usually produces the red/green/blue sequence
    * podo      - A terminal-independent sequence of eight colors, intended to
                  be easy for color-blind people to distinguish

Tip: Because the three built-in color sequences aren't very good, you should
consider defining and using a custom sequence.

Color specifications tend to be clumsy; they're both lengthy and obscure. It may
therefore be a good idea to introduce shorthands.

Instead of using a hex string, you can assign its value to a semantically named
variable:

    gold = "#ffd700"                <---- Hex string
    gold = pack(0xff, 0xd7, 0)      <---- Equivalent: integer value
    plot "data" u 1:2 w l lc rgb gold

This isn't ideal, because you still have to type the keyword rgb every time. You
can absorb it into the variable if you use gnuplot's macro facility.

    blue = "rgb '#0000ff'"
    plot "data" u 1:2 w l lc @blue

You can even include the lc keyword in the macro:

    green = "lc rgb 'green'"
    plot "data" u 1:2 w l @green

Rather than use color names, you may also want to consider semantic names for
colors:
    alarm = "red"
    normal = "#00cd00"

# 2D plot of matrix data
Plot a matrix in gnuplot having such data structure, using the first row and
column as a x and y ticks (the first number of the first row is the number of
columns) and represent the rest of the values by a color mapping so it can be
seen on a 2D plane.

* with image
(regular grid, no interpolation, one quadrangle for each data point)
    set autoscale xfix
    set autoscale yfix
    set autoscale cbfix
    plot 'data' matrix nonuniform with image notitle

* with pm3d
(supports also irregular grids and interpolation, plots one quadrangle for four
neighboring data points)
    set autoscale xfix
    set autoscale yfix
    set autoscale cbfix
    set pm3d map
    splot 'data' matrix nonuniform notitle


# pass gnuplot a matrix in C

#include <stdio.h>
int main(void) {
    FILE *gp = popen("gnuplot -persist", "w");
    fprintf(gp, "plot '-' matrix with image pixels notitle\n");
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++)
            fprintf(gp, "%d ", matrix[i][j]);
        fprintf(gp, "\n");
    }
    pclose(gp);
    return 0;
}
