Cookbook
One task per recipe: the script (or program), and the plot it writes. The scripts read the logs of the tutorial solver, run.dat and run.csv, and a few small files; run any of them with foresight SCRIPT. Every plot here is regenerated from its recipe by scripts/docs_examples.sh and checked by the CI.
Data and columns
Two columns of a file
set terminal svg size 560,320; set output 'cb_columns.svg'
plot 'run.dat' using 1:5 with lines title 'cd'A single column
set terminal svg size 560,320; set output 'cb_single_column.svg'
# one column: x is the point number, as using 0:1
plot 'single.dat' with linespoints pt 7With one column, x is the point number, as using 0:1; using 2 alone does the same for column 2.
One point every N
set terminal svg size 560,320; set output 'cb_every.svg'
set logscale y
plot 'run.dat' u 1:2 every 10 with linespoints pt 6 title 'every 10th iteration'every I:J:K:L:M:N is gnuplot's full form: point and block increments, first and last points and blocks.
One dataset of a file
set terminal svg size 560,320; set output 'cb_index.svg'
set key bottom right
plot 'probes.dat' index 0 with lp pt 5 title 'run 1', '' index 1 with lp pt 9 title 'run 2'Two blank lines separate datasets; index N (0-based) picks one.
Scale and shift columns
set terminal svg size 560,320; set output 'cb_expression.svg'
set xlabel 'time [min]'; set ylabel 'cd [counts]'
plot 'run.dat' using ($1 * 0.5 / 60):($5 * 1e4) title 'cd'A parenthesized field is an expression evaluated per row: $N is column N, $0 the point number.
Keep only some points
set terminal svg size 560,320; set output 'cb_filter.svg'
# 1/0 is undefined: those points are gaps
plot 'run.dat' using 1:($5 > 0.3 ? $5 : 1/0) with points pt 7 title 'cd above 0.3'1/0 is undefined: the point is dropped, a gap in a line.
CSV with a header row
set terminal svg size 560,320; set output 'cb_csv_header.svg'
set datafile separator comma
set logscale y
plot 'run.csv' using "iteration":"continuity" title columnhead, '' using 1:"energy" title columnheadQuoted names select columns by header; title columnhead titles with the header of the y column. set key autotitle columnhead does it for every item.
Missing values and other comment marks
set terminal svg size 560,320; set output 'cb_missing.svg'
set datafile commentschars "%"
set datafile missing "-"
plot 'sensor.dat' u 1:2 w lp t 'inlet', '' u 1:3 w lp t 'outlet'The - cells are missing data: those points are left out and the lines go on; % starts the comments of this file.
A binary log
set terminal svg size 560,400; set output 'cb_binary_log.svg'
# a solver's binary log: records of an int32 iteration and two float64 residuals, read as gnuplot's binary format
set title 'residuals from a binary log'
set logscale y
set format y '10^{%L}'
set xlabel 'iteration'
set ylabel 'residual'
plot 'residuals.bin' binary format='%int32%float64%float64' using 1:2 with lines lw 2 title 'continuity', \
'residuals.bin' binary format='%int32%*float64%float64' using 1:2 with lines lw 2 title 'momentum'A solver writes its residuals as binary records (an int32 iteration and two float64 residuals, Fortran's access= 'stream'): binary format='...' reads them as gnuplot 6.0 does, using taking the fields as columns, %*float64 dropping one. See Binary files.
Text columns: names and labels
set terminal svg size 560,320; set output 'cb_strcol.svg'
# the text of column 1 names the bars and labels them with the speedup; one solver chosen by its name
set style fill solid 0.6 border -1; set yrange [0:5]; set key top left
plot 'runs.dat' u 0:4:xtic(strcol(1) . "\n" . sprintf('%.0e', $2)) w boxes t 'speedup', \
'' u 0:($4 + 0.25):(sprintf('%.0f s', $3)) w labels notitle, \
'' u 0:(strcol(1) eq 'multigrid' ? $4 : 1/0) w p pt 7 ps 2 t 'multigrid'strcol(1) is the text of column 1: joined with a formatted number on a second line it names each bar (xtic), in sprintf it builds the label of each bar (with labels), compared with eq it keeps one solver. See String columns.
Data inside the script
set terminal svg size 560,320; set output 'cb_datablock.svg'
# data written inside the script: a datablock, plotted, fitted and measured as a file
$CONV << EOD
# h error
0.1 2.10e-3
0.05 5.30e-4
0.025 1.29e-4
0.0125 3.33e-5
0.00625 8.20e-6
EOD
f(x) = c * x**p; c = 1; p = 1
fit f(x) $CONV u 1:2 via c, p
stats $CONV u 2 nooutput
set logscale xy; set format y '%h'; set key top left
set xlabel 'h'; set ylabel 'error'
plot $CONV u 1:2 w lp pt 7 t sprintf('%d errors', STATS_records), f(x) dt 2 t sprintf('order %.2f', p)A datablock keeps the data in the script itself: plot, fit and stats read $CONV as a file. See Datablocks and scripts.
Data after the plot command
set terminal svg size 560,320; set output 'cb_inline_data.svg'
# inline data '-': the lines after the plot, up to one starting with e, one block per '-' item
set key top left
plot '-' using 1:2 with linespoints pt 7 t 'first block', '-' with points pt 5 ps 1.4 t 'second block'
1 1.0
2 2.5
3 2.9
4 4.2
e
1.5 2.0
3.5 3.1
e'-' reads the data from the lines after the statement, gnuplot's inline data: up to a line starting with e, one block per '-' item, in order. See Datablocks and scripts.
A script with arguments
set terminal svg size 760,300; set output 'cb_call.svg'
# one panel script called with arguments (files/panel.gp: ARG1 the column, ARG2 the title)
set multiplot layout 1,2
call 'panel.gp' 2 'continuity'
call 'panel.gp' 3 'momentum'
unset multiplot# a panel of the run: column ARG1 of run.dat, titled ARG2 (called by cb_call.gp)
set title ARG2
set logscale y
plot 'run.dat' u 1:(column(ARG1 + 0)) w l lw 2 t ARG2call runs panel.gp with ARG1 the column and ARG2 the title; column(ARG1 + 0) reads the column the string names. From the shell, foresight -c panel.gp 2 continuity does the same.
Arrays
set terminal svg size 560,320; set output 'cb_arrays.svg'
# arrays: filled in a loop, plotted and stated as a file, indexed by a data column
array T[8]
do for [i = 1:|T|] { T[i] = 300 + 40 * (1 - exp(-0.4 * i)) }
array where = ['inlet', 'throat', 'exit']
stats T nooutput
set title sprintf('%d probes (%s to %s), mean %.1f K', |T|, where[1], where[|where|], STATS_mean)
set xlabel 'probe'; set ylabel 'T [K]'; set key bottom right; set xrange [0:9]
plot T w lp pt 7 t 'T', T u 1:(T[$1] - STATS_mean + 300) w lp dt 2 t 'T - mean + 300'An array is filled in a loop, |T| its size; plot T and stats T read the index and the value of each element as a file, T[$1] indexes it by a data column. See Arrays.
Array slices
set terminal svg size 560,320; set output 'cb_slices.svg'
# twelve monthly values, the quarters as slices: printed, sized, averaged
array M = [3.1, 3.4, 4.0, 5.2, 6.8, 8.1, 8.9, 8.6, 7.2, 5.6, 4.1, 3.3]
array Q[4]
do for [q = 1:4] { S = M[3*q - 2:3*q]; Q[q] = (S[1] + S[2] + S[3]) / |S| }
print M[1:3], M[10:]
set xrange [0:13]; set xlabel 'month'; set key top left
set title sprintf('%d months, summer mean %.2f', |M|, Q[3])
plot M w lp pt 7 t 'month', Q u (3*$1 - 1):2 w p pt 5 ps 2 t 'quarter mean'M[3*q - 2:3*q] is the array of a quarter's months, a copy assigned to S; M[1:3] and M[10:] print as arrays and |S| is a slice's size. See Slices.
Shell commands and reset
set terminal svg size 760,300; set output 'cb_runtime.svg'
# a title from shell commands, then reset: the second panel is back to the defaults
host = system('echo solver-7')
n = `grep -vc '^#' live.dat`
set multiplot layout 1,2
set title sprintf('%s: %d log lines', host, n); set logscale y; set format y '%h'; set grid; set key off
plot 'live.dat' u 3:4 w l lw 2
reset
set title 'after reset'
plot 'live.dat' u 3:4 w l lw 2
unset multiplotsystem('...') and a command between backquotes give the output of a shell command (the run's host, the lines of the log); reset puts the settings back to their defaults for the next panel. See Shell commands, reset and pause.
A plot that follows a run
set terminal svg size 560,320; set output 'cb_live_loop.svg'
# gnuplot 6.0's live loop: plot, pause, plot again (a real one is while (1) { ... }; here three passes)
set logscale y; set format y '%h'; set xlabel 'iteration'; set ylabel 'residual'
pass = 0
while (pass < 3) {
pass = pass + 1
set title sprintf('pass %d: %d iterations', pass, 80 * pass)
plot 'live.dat' u 3:($3 <= 80 * pass ? $4 : 1/0) w l lw 2 t 'residual'
pause 0.1
}gnuplot 6.0's live loop: each pass plots and pauses, the output rewritten at each plot. A real one is while (1) { plot ...; pause 5 } with set terminal html refresh 5: the page in the browser follows the run (foresight --watch does the same without a loop, see Monitoring).
A table of a plot
set terminal svg size 560,320; set output 'cb_table.svg'
# a smoothed curve tabulated into a datablock, then plotted with the samples (a marker every 10 points)
set table $SMOOTH
plot 'noisy.dat' u 1:2 smooth csplines
unset table
set title sprintf('the spline, %d tabulated lines', |$SMOOTH|); set key bottom left
plot 'noisy.dat' u 1:2 w p pt 7 t 'samples', $SMOOTH u 1:2 w lp pi 10 pt 6 lw 2 t 'set table $SMOOTH, pi 10'set table $SMOOTH makes the plot write its points into the datablock, in gnuplot's table layout, instead of drawing them; plotted afterwards they are the spline itself, a marker every 10 points (pi 10). See Tables.
Rows as text
set terminal svg size 560,320; set output 'cb_with_table.svg'
# the slow steps of a run as text (with table if ...), then plotted over the whole run
set table $SLOW
plot 'steptimes.dat' u 1:2 w table if $2 > 1.6
unset table
print $SLOW[1], ' ... ', |$SLOW|, ' slow steps'
set xlabel 'step'; set ylabel 'wall time [s]'; set yrange [1:2]; set key top left
plot 'steptimes.dat' u 1:2 w l t 'every step', $SLOW u 1:2 w p pt 7 t 'with table if $2 > 1.6'$ foresight cb_with_table.gp
25 1.661 ... 12 slow steps
foresight: cb_with_table.svgwith table if $2 > 1.6 writes the rows of the slow steps, as text, into the datablock: the using fields, each after a blank, tab separated. Plotted over the whole run, they mark the steps that wrote a file. See With table.
Values printed into a datablock
set terminal svg size 560,320; set output 'cb_print_datablock.svg'
# a convergence table computed in a loop, printed into a datablock, then plotted
set print $ERR
do for [n = 1:6] { h = 0.4 / 2**n; print h, h**2 * (1 + h) }
set print
set logscale xy; set format y '%.0e'; set key top left
set xlabel 'h'; set ylabel 'error'
plot $ERR u 1:2 w lp pt 7 t 'set print $ERR', x**2 dt 2 t 'h^2'set print $ERR sends the lines printed in the loop to a datablock, which then plots as data: a table computed by the script itself. See Print.
Random numbers
set terminal svg size 560,320; set output 'cb_random.svg'
# gnuplot's own random numbers (the same as gnuplot's from the same seed): three walks printed into a datablock
x = rand(7)
set print $WALK
do for [w = 1:3] { y = 0; do for [i = 0:200] { y = y + (rand(0) < 0.5 ? -1 : 1); print i, y }; print ""; print "" }
set print
if (!exists("steps")) steps = 200
set xrange [0:steps]; set xlabel 'step'; set ylabel 'position'; set xzeroaxis; set key bottom left
plot $WALK index 0 w l lw 1.5 t 'walk 1', '' index 1 w l lw 1.5 t 'walk 2', '' index 2 w l lw 1.5 t 'walk 3'rand(7) seeds gnuplot's generator, rand(0) draws the next number: the walks are the ones gnuplot draws from the same seed. exists("steps") lets a caller set the length first. See Expressions in using.
Axes, ticks and key
A log axis with exponent labels
set terminal svg size 560,320; set output 'cb_logscale.svg'
set logscale y
set format y '%.0e'
set grid
plot 'run.dat' u 1:2 t 'continuity'A reversed axis
set terminal svg size 560,320; set output 'cb_reversed.svg'
# min > max reverses the axis
set xrange [120:0]
plot 'run.dat' u 1:5 t 'cd'Limits of the autoscale
set terminal svg size 560,320; set output 'cb_autoscale_limits.svg'
# limits of the autoscaled ends: y at least from -1 to 1, x within [0:12] whatever the data
$D << EOD
-2 0.2
3 0.5
8 0.4
15 0.6
EOD
set yrange [*<-1:1<*]
set xrange [0<*:*<12]
plot $D with linespoints pt 7 lw 2 title '[0<*:*<12] x [*<-1:1<*]'lb<* and *<ub keep an autoscaled end within limits: the y range spans at least -1 to 1, the x range autoscales within 0 to 12 whatever the data. See Grid, zero axes and border.
Tick steps and label formats
set terminal svg size 560,320; set output 'cb_ticks.svg'
set xtics 0,30,120
set ytics 0.1
set format y '%.2f'
plot 'run.dat' u 1:5 t 'cd'On a log axis the step is a factor: set ytics 10 puts a tick every decade.
Ticks without labels
set terminal svg size 560,320; set output 'cb_format_none.svg'
# set format y "": the ticks kept, their labels hidden; a format without conversion writes its text at every tick
set format y ""; set format x "|"; set grid; set key off
plot sin(x) lw 2set format y "" keeps the ticks and drops their labels (and their margin); a format without a conversion writes its text at every tick. See Ticks and label formats.
Powers of ten and unit prefixes
set terminal svg size 560,320; set output 'cb_format_powers.svg'
# powers of ten as superscripts on a log axis, SI prefixes on a linear one (gnuplot's %T and %s %c)
set logscale y; set format y "10^{%T}"
set format x "%.1s %cHz"; set xlabel 'frequency'; set ylabel 'gain'
set xrange [0:2e6]; set yrange [1e-2:1e4]
plot 1e4 / (1 + (x/2e5)**2) lw 2 t 'low pass, 200 kHz'gnuplot's %T is the power of ten of a value, as a superscript with enhanced text; %s its mantissa to a power of 1000 and %c the SI prefix of that power. See Ticks and label formats.
Ticks on the axes, a range frame
set terminal svg size 640,300; set output 'cb_tics_axis.svg'
# ticks on the axes through the origin; a range frame: ticks and border sides within the data range
$RUNS << EOD
0.5 1.1
1.5 1.9
2.5 2.1
3.5 3.0
4.5 3.2
EOD
set multiplot layout 1,2
set xtics axis; set ytics axis; set key top left
plot [-6:6] [-1.2:3.2] 3*sin(x)/x t '3 sinc(x)'
set xtics border nomirror rangelimited; set ytics border nomirror rangelimited; set border 3
plot [0:5] [0:4] $RUNS w lp pt 7 lw 2 t 'runs'
unset multiplotset xtics axis draws the ticks on y = 0, set ytics axis on x = 0, their labels taking no margin; rangelimited keeps the ticks and the border side within the data. See Ticks and label formats.
Room around the data, the date of the plot
set terminal svg size 560,320; set output 'cb_offsets.svg'
# room around the data (set offsets) and the date of the plot in the corner (set timestamp)
$RUNS << EOD
1 4.2
2 5.1
3 4.7
4 6.3
5 5.9
EOD
set offsets 0.5, 0.5, 1, 1
set timestamp "plotted %Y-%m-%d" bottom
plot $RUNS w lp pt 7 lw 2 t 'runs'set offsets moves the autoscaled ends out before the extension to the ticks; set timestamp writes the date (here the documentation's fixed SOURCE_DATE_EPOCH). See Offsets and Margins.
Named ticks and extra ticks
set terminal svg size 560,320; set output 'cb_tics_list.svg'
set xtics ("Jan" 1, "" 1.5 1, "Feb" 2, "" 2.5 1, "Mar" 3, "" 3.5 1, "Apr" 4, "" 4.5 1, "May" 5, "" 5.5 1, "Jun" 6)
set ytics add ("alert" 75, "%.0f mm" 45)
set grid
set yrange [30:90]
plot 'rain.dat' u 1:2 w linespoints t 'rain'An explicit list replaces the ticks: names at chosen positions, "" with level 1 for an unlabelled minor tick. With add the list joins the automatic ticks; a label holding a conversion is the format of its position ("%.0f mm").
A rug of ticks
set terminal svg size 560,360; set output 'cb_rug.svg'
# a rug plot: empty tic labels are ticks too, one per row on each axis (xtic("") and ytic(""))
set samples 60
set xtics out scale 2 nomirror; set ytics out scale 2 nomirror
set xrange [-3:3]; set yrange [-3:3]; unset key
plot '+' using (2*sin($1*7.3)):(2*cos($1*3.1)):xtic(""):ytic("") with points pt 7 ps 0.6An empty tic label is still a tick: xtic("") and ytic("") mark every row on both axes, a rug plot. See Text labels on any axis.
Names on the y axis
set terminal svg size 560,320; set output 'cb_ytic.svg'
# the stations named on the y axis (ytic), their wind speed on x
set title 'wind speed by station'; set xlabel 'speed [m/s]'; set key off
set xrange [0:2]; set yrange [-0.5:4.5]
plot 'stations.dat' u (0):0:3:(0) w vectors nohead lw 3, '' u 3:0:ytic(5) w p pt 7 ps 2ytic(5) names the y ticks with column 5 at the ordinates (the point numbers here), as xtic does the x ones; x2tic and y2tic need set x2tics and set y2tics. See Text labels on any axis.
Minor ticks
set terminal svg size 560,320; set output 'cb_mtics.svg'
set logscale y
set mxtics 4
set mytics
plot 'run.dat' u 1:2 t 'continuity', '' u 1:3 t 'momentum'set mxtics 4 divides each step of x in 4; set mytics alone takes gnuplot's count, 9 per decade on a log axis.
Rotated labels and outward ticks
set terminal svg size 560,320; set output 'cb_tics_rotate.svg'
set style fill solid 0.6
set boxwidth 0.6
set xtics rotate by 30 right out nomirror
set ytics out nomirror
set xrange [-0.6:4.6]; set yrange [0:*]
plot 'throughput.dat' u 1:3:xtic(2) w boxes t 'time [s]'Long category names fit rotated: rotate by 30 right ends each label at its tick, below the axis. out points the ticks away from the plot; nomirror leaves the opposite border bare.
Rotated y labels
set terminal svg size 560,320; set output 'cb_ytics_rotate.svg'
# long y tick labels read upward (rotate), the y2 ones turned by 45 degrees: narrower margins
set ytics 500 rotate format "%.0f MB/s" nomirror
set y2tics 3 rotate by 45 format "%.1f s"
set xrange [1:64]
set yrange [0:1600]; set y2range [0:12]
set key top left
plot 25*x title 'bandwidth' lw 2, 12/sqrt(x) axes x1y2 title 'latency' lw 2set ytics rotate turns long y labels to read upward, centred on their ticks, so the left margin stays narrow; rotate by 45 turns them by an angle, right-justified (on y2, left-justified), as gnuplot places them. See Ticks and label formats.
A time axis
set terminal svg size 640,480; set output 'cb_time.svg'
# a log stamped with the wall clock: the time spans two columns (y is column 4), ticks in whole time units
set xdata time; set timefmt '%Y-%m-%d %H:%M:%S'
set multiplot layout 2,1
set title 'labels invented by gnuplot rules'; set logscale y; set format y '%h'
plot 'live.dat' u 1:4 w l lw 2 t 'residual'
set title "set format x '%H:%M', a 30 minutes step"; unset logscale y; set format y '%g'
set format x '%H:%M'; set xtics 1800; set xrange ['2024-03-01 10:00:00':'2024-03-01 12:00:00']
plot 'live.dat' u 1:5 w l lw 2 t 'cd'
unset multiplotset xdata time reads the x field with the timefmt: the time spans two columns, so the residual is column 4. The ticks fall on whole time units, the labels invented from the range as gnuplot's (%H:%M:%S within a day at minute steps), or written by set format x; range ends are times. See Time data.
Geographic tick labels
set terminal svg size 560,400; set output 'cb_geographic.svg'
# a great-circle route labelled in degrees and compass letters (set xtics geographic)
set xrange [-180:180]; set yrange [-90:90]
set xtics 60 geographic; set format x "%D°%E"
set ytics 30; set format y "%D°%N" geographic
set grid
set size ratio 0.5
set title 'Lisbon to Tokyo'
lon(t) = -9.14 + t*(139.69 + 9.14)
lat(t) = 38.72 + (35.68 - 38.72)*t + 30*sin(pi*t)
set samples 100
plot sample [t=0:1] '+' using (lon($1)):(lat($1)) with lines lw 2 notitle, \
'-' using 1:2:3 with labels point pt 7 offset 1,1 notitle
-9.14 38.72 Lisbon
139.69 35.68 Tokyo
eset xtics geographic writes the tick labels in degrees, minutes and seconds by the format: %D the whole degrees, %E E or W and %N N or S in place of the sign, as gnuplot's gstrdms. See Geographic tick labels.
Minor ticks in time units
set terminal svg size 640,260; set output 'cb_time_minor.svg'
# a minor tick every 10 minutes of the wall clock, whatever the major step
set xdata time; set timefmt '%Y-%m-%d %H:%M:%S'; set format x '%H:%M'
set mxtics time 10 minutes
set title 'set mxtics time 10 minutes'; set logscale y; set format y '%h'; set key off
plot 'live.dat' u 1:4 w l lw 2set mxtics time 10 minutes (gnuplot 6.0) puts a minor tick at every 10 minutes of the clock, whatever the major step; time 1 months marks the first of every month.
Week dates
set terminal svg size 640,300; set output 'cb_weekdates.svg'
# weekly counts keyed by ISO 8601 week dates ("2021-W05"), placed on a time axis
calendar(w) = weekdate_iso(int(w[1:4]), int(w[7:8]))
$WEEKLY << EOD
2020-W50 31
2020-W51 44
2020-W52 52
2020-W53 47
2021-W01 61
2021-W02 58
2021-W03 49
2021-W04 37
2021-W05 30
2021-W06 22
2021-W07 18
2021-W08 15
EOD
set xtics time format "%d %b\n%Y"; set ytics nomirror; set border 3; set key off
set title sprintf("week 1 of 2021 starts on %s (tm\\_week of 1 January 2021: %d)", \
strftime("%a %d %b", weekdate_iso(2021, 1)), tm_week(strptime("%Y-%m-%d", "2021-01-01"), 0))
plot $WEEKLY using (calendar(strcol(1))):2 with linespoints pt 7 lw 2weekdate_iso(year, week [, day]) gives the time of an ISO 8601 week date (weeks from Monday, week 1 the one of the first Thursday: 2021-W01 starts on 4 January), weekdate_cdc the CDC epidemiological one (from Sunday), and tm_week(t, 0|1) the week of a time, as gnuplot 6.0; tm_mday, tm_mon and the other tm_* give its fields. See Time data.
Two y axes
set terminal svg size 560,320; set output 'cb_y2.svg'
set logscale y; set ytics nomirror; set y2tics
plot 'run.dat' u 1:2 t 'residual', '' u 1:5 axes x1y2 t 'cd'Two x axes
set terminal svg size 560,320; set output 'cb_x2.svg'
set xrange [0:100]; set xtics nomirror; set xlabel 'frequency [Hz]'
set x2range [0:2]; set x2tics 0.25; set x2label 'Strouhal number fD/U (D = 0.1 m, U = 5 m/s)'
# the same peaks plotted against x2 (axes x2y1): f D / U = 0.02 f lands each on its impulse
plot 'spectrum.dat' w impulses lw 2 t 'lift spectrum', \
'' u ($1*0.02):2 axes x2y1 w p pt 7 ps 0.6 t 'against St (axes x2y1)'The top border in another unit: the x2 axis takes the x2range given, here the frequency scaled to the Strouhal number. The points are the same peaks plotted axes x2y1, against x2: each lands on its impulse, the check that the two scales agree. Without a set x2range, items on x2 autoscale it on their own.
A broken axis
set terminal svg size 560,320; set output 'cb_nonlinear_axis.svg'
# set nonlinear x: a broken axis, the gap between 100 and 500 left out (f undefined there)
gap = 25.
f(x) = (x <= 100) ? x : (x < 500) ? NaN : (x - 400 + gap)
g(x) = (x <= 100) ? x : (x < 100 + gap) ? NaN : (x + 400 - gap)
set xrange [15:600] noextend
set nonlinear x via f(x) inverse g(x)
set xtics 50; set border 3; set xtics nomirror; set ytics nomirror; set key top right
$LOAD << EOD
20 3.1
40 2.6
60 2.2
80 1.9
100 1.7
520 0.9
540 0.85
560 0.82
580 0.8
EOD
plot $LOAD using 1:2 with linespoints pt 7 t 'residual'set nonlinear x via f(x) inverse g(x) places the axis linearly in f: here f leaves out 100 to 500, a broken axis. Its automatic ticks sit at the hidden axis' ticks, a step or a list in the axis' own values. See Ticks and label formats.
A top axis linked to the bottom one
set terminal svg size 560,360; set output 'cb_linked_axes.svg'
# set link x2 via ... inverse ...: the top axis a function of the bottom one, here wavelength and wavenumber
set xlabel 'wavelength [um]'; set x2label 'wavenumber [1/cm]'
set link x2 via 1e4/x inverse 1e4/x
set xrange [2:20]; set xtics nomirror; set x2tics; set key top right
plot 1.0/(1 + ((x - 8)/2)**2) lw 2 t 'absorption band'set link x2 via F(x) inverse G(x) maps the bottom axis onto the top one: wavenumber = 10⁴ / wavelength. As gnuplot 6.0, the top ticks sit at the bottom axis' automatic ticks, labelled by their mapped values. See Second x axis.
Rotated labels on top
set terminal svg size 560,340; set output 'cb_x2_rotate.svg'
set xrange [0:100]; set xtics nomirror; set xlabel 'frequency [Hz]'
# the same axis read as periods on top: named ticks, rotated to fit
set x2range [0:100]
set x2tics ("40 ms" 25, "20 ms" 50, "13.3 ms" 75, "10 ms" 100) rotate by 45 out
set x2label 'period'
plot 'spectrum.dat' w impulses lw 2 t 'lift spectrum'Named x2 ticks read the frequency axis as periods; rotate by 45 turns them from their tick, away from the plot, and the top margin grows to fit them. See Ticks.
The key below the plot
set terminal svg size 560,320; set output 'cb_key.svg'
set key below box
set logscale y
plot 'run.dat' u 1:2 t 'continuity', '' u 1:3 t 'momentum', '' u 1:4 t 'energy'outside moves the key to the right margin (or outside left, outside top center, ...); below and above lay it out in rows.
The key at a position
set terminal svg size 560,320; set output 'cb_key_at.svg'
set logscale y
# the top left corner of the key at iteration 60, residual 1 (data coordinates); graph or screen fractions also work
set key at 60, 1 left top box
plot 'run.dat' u 1:2 t 'continuity', '' u 1:3 t 'momentum', '' u 1:4 t 'energy'at puts the key where the data leave room: left top aligns its top left corner on the point, in data coordinates by default, graph or screen fractions otherwise. lmargin, rmargin, tmargin and bmargin put it in a margin instead. See Key.
No key
set terminal svg size 560,320; set output 'cb_no_key.svg'
unset key
plot 'run.dat' u 1:5, '' u 1:5:6 every 10 with yerrorbarsnotitle keeps one item out of the key; set key noautotitle all the untitled ones.
Titles at the curves
set terminal svg size 560,320; set output 'cb_title_at.svg'
# titles at the end of their curves (no key), as gnuplot's title ... at end
unset key
set rmargin 10
set xrange [0:10]
plot for [k=1:4] k*sqrt(x) lw 2 title sprintf('k = %d', k) at endtitle ... at end writes each title after the last point of its curve, with or without the key (at beginning before the first one; at X,Y a key entry at a screen position). See Key.
A key in its own layout
set terminal svg size 560,320; set output 'cb_key_layout.svg'
# a key in its own layout: samples left of the titles, left-justified, last run first, painted over the curves
set key top right box opaque reverse Left invert samplen 2 width 1 title "runs" offset 0,-0.5
set xrange [0:10]; set yrange [0:1.1]; set xlabel 't [s]'
plot for [k = 1:4] 1 - exp(-k*x/4) lw 2 t sprintf('run %d, tau = %.1f s', k, 4./k)reverse puts the samples first and Left justifies the titles, invert lists the last run first, opaque paints the key over the curves passing under it, title names it. See Key.
A key in columns
set terminal svg size 560,320; set output 'cb_key_columns.svg'
# a key of 3 rows a column, the titles in their series' colors, a styled box
set key top left box lt 4 lw 1.5 maxrows 3 spacing 1.2 tc variable
set xrange [0:4]
plot for [k=1:7] x**(k/3.) lw 2 t sprintf('x^{%d/3}', k)maxrows 3 starts a column every 3 entries, tc variable writes each title in its series' color, lt 4 lw 1.5 styles the box. See Key.
Key entries of their own
set terminal svg size 560,320; set output 'cb_keyentry.svg'
# key entries of their own (keyentry) for a boxplot and error bars; set style data filledcurves y=0 for the data
set style fill solid 0.4
set style data filledcurves y=0
set key top left
$D << EOD
0 1
1 3
2 2
3 4
EOD
plot keyentry with boxplot lc 3 title 'boxplot sample', keyentry with yerrorbars lc 4 title 'error bars', \
$D lc 1 title 'data (filledcurves y=0)'keyentry adds a key entry with no data, here the samples of a boxplot and of error bars; set style data filledcurves y=0 gives the data items their fill to y = 0. See Key.
Key samples of vectors, fills and labels
set terminal svg size 560,320; set output 'cb_key_samples.svg'
# key samples as gnuplot 6.0: an arrow for vectors, none for a keyentry of labels, the fill border around a fill
$V << EOD
1 1 1 0.5
2 2 1 -0.4
4 1 -1 0.6
EOD
set key title 'samples' left box; set style fill solid 0.3 border lc 'black'; set xrange [0:6]; set yrange [0:3.5]
plot $V using 1:2:3:4 with vectors lw 2 t 'vectors', $V using 1:2 with filledcurves y=0 t 'filledcurves', \
keyentry with labels t 'labels (no sample)'The key samples are gnuplot 6.0's: an arrow for vectors, a filled box with the fill style's border, none for a keyentry of labels; set key title "..." left puts the title at the left of the key. See Key.
Key columns, label offsets, a title on the right
set terminal svg size 560,320; set output 'cb_key_options.svg'
# the key in two columns, the y label moved and colored, the title on the right
set key top right columns 2 box
set ylabel 'amplitude' offset 1,0 tc rgb '#0072b2'
set title 'Bessel functions' right
set xrange [0:20]; set yrange [-1:1.6]
plot besj0(x), besj1(x), besy0(x), besy1(x)set key columns N lays the key out in N columns; set ylabel "..." offset X,Y tc COLOR moves (in characters) and colors a label; set title "..." right justifies the title about its centre, as gnuplot. See Key and Titles and labels.
Enhanced text: sub and superscripts, Greek letters
set terminal svg size 560,340; set output 'cb_enhanced.svg'
# gnuplot's enhanced text: sub and superscripts, Greek letters, sizes, bold and italic; noenhanced as it is
set title "{/:Bold Decay} of u(t) = u_0 e^{-t/{/Symbol t}}"
set xlabel "t / {/Symbol t}"; set ylabel "u / u_0"
set xrange [0:4]; set yrange [-0.6:1.1]
set xtics ("0" 0, "{/Symbol t}" 1, "2{/Symbol t}" 2, "3{/Symbol t}" 3, "4{/Symbol t}" 4)
set label 1 "{/:Italic half life} t_{1/2} = {/Symbol t} ln 2" at 0.8,0.55
set label 2 "run_07/u_probe.dat" at 2.3,-0.45 noenhanced
plot exp(-x) lw 2 t "e^{-t/{/Symbol t}}", exp(-x)*cos(2*pi*x) lw 2 t "e^{-t/{/Symbol t}} cos 2{/Symbol p}t"gnuplot's markup, on by default: _0 and ^{...} sub and superscripts, {/Symbol t} a Greek τ, {/:Bold ...} and {/:Italic ...}, also in the tick labels of a list. noenhanced writes a file name with its underscores as it is; the automatic titles stay as they are. See Enhanced text.
Grid lines, zero axes and border
set terminal svg size 560,320; set output 'cb_grid_zero.svg'
# major and minor grid lines in their own style, the zero axes, a two-sided thicker border, x ends at the data
set mxtics 5; set mytics 5
set grid x y mx my lc 'gray' lw 0.5 dt 3
set xzeroaxis lw 1.5; set yzeroaxis lw 1.5
set border 3 lw 1.5; set tics out nomirror scale 1.5, 0.75
set autoscale xfix; set key bottom right
plot [-2*pi:2*pi] sin(x)*exp(-0.1*x) t 'sin(x) exp(-x/10)', cos(x) t 'cos(x)'Grid lines at the major and minor ticks in their own style, the lines at x = 0 and y = 0, the left and bottom sides of the border only, outward ticks longer than the default, x ends at the data (set autoscale xfix). See Grid, zero axes and border.
One unit as long on both axes
set terminal svg size 560,360; set output 'cb_size_square.svg'
# set size ratio -1: one unit as long on x as on y, a circle round whatever the ranges
set size ratio -1
set parametric; set trange [0:2*pi]; set samples 200
set xrange [-3:3]; set yrange [-1.2:1.2]; set grid; set key top right
plot cos(t), sin(t) lw 2 t 'unit circle', 2*cos(t), 0.5*sin(t) lw 2 t 'ellipse 2 x 0.5'set size ratio -1 makes a unit of y as long as a unit of x, whatever the ranges: the circle stays round. ratio -R makes a y unit R times an x unit. See set options.
A grid of panels
set terminal svg size 560,420; set output 'cb_multiplot.svg'
set multiplot layout 2,1
set logscale y; plot 'run.dat' u 1:2 t 'continuity'
unset logscale y; plot 'run.dat' u 1:5 t 'cd'
unset multiplotPanels lined up
set terminal svg size 560,360; set output 'cb_margins.svg'
# two panels lined up whatever their tick labels: the same left and right borders at screen fractions
set multiplot layout 2,1
set lmargin at screen 0.16; set rmargin at screen 0.96
set ylabel 'continuity'; set logscale y; set format y '%.0e'
plot 'run.dat' u 1:2 w l t 'continuity'
unset logscale y; set format y '%g'; set ylabel 'energy x 1e6'; set xlabel 'iteration'
plot 'run.dat' u 1:($3*1e6) w l lc 2 t 'energy'
unset multiplotThe same left and right borders at screen fractions line up the two panels, although the log labels of the first are wider. See Margins.
Panels column by column
set terminal svg size 560,360; set output 'cb_multiplot_order.svg'
# panels filled column by column from the bottom row: columnsfirst upwards
set multiplot layout 2,2 columnsfirst upwards title 'columnsfirst upwards' font ',12'
set ytics 1
do for [k = 1:4] {
set title sprintf('panel %d', k)
plot sin(k*x) notitle
}
unset multiplotset multiplot layout R,C columnsfirst upwards fills the grid column by column from the bottom row (rowsfirst and downwards are the defaults). See Multiplot.
An inset on a cleared box
set terminal svg size 560,400; set output 'cb_inset_clear.svg'
# an inset on a cleared box (clear), its key headed by a text entry (keyentry "text")
set multiplot
set title 'damped oscillation'
set samples 400
set key bottom right
plot [0:20] exp(-x/6)*cos(2*x) lw 2 title 'signal'
set origin 0.52, 0.5; set size 0.42, 0.38
clear
unset title
set key top right samplen 2
set xtics 1; set ytics 0.5
plot [0:3] exp(-x/6)*cos(2*x) lw 2 notitle, keyentry 'detail' font ':Bold', keyentry with lines lc 'gray50' title 't < 3'
unset multiplotIn a multiplot, clear paints the box of the next plot (set origin, set size) with the page color, so the inset is not crossed by the curve below, as gnuplot. keyentry "text" adds a key entry whose sample is the text itself, a header for the entries after it. See Multiplot.
Panels with margins and spacing
set terminal svg size 560,400; set output 'cb_multiplot_margins.svg'
# a layout whose plot areas line up: margins (screen fractions) and spacing between them
set multiplot layout 2,2 margins 0.1, 0.97, 0.1, 0.9 spacing 0.07, 0.1 title 'aligned plot areas'
unset key
plot sin(x)
plot cos(x)
plot sin(2*x) * 100
plot cos(2*x) * 100
unset multiplotmargins L,R,B,T puts the plot areas of the layout in that box of the page (screen fractions, or characters after char), spacing X,Y apart: the plot areas line up whatever the tick labels. See Multiplot.
Lines, points and error bars
Special functions
set terminal svg size 720,480; set output 'cb_special_functions.svg'
# gnuplot's special functions: Bessel, gamma, error and normal, Lambert W and Airy
set multiplot layout 2,2
set key bottom left; set title 'Bessel'
plot [0:20] besj0(x) t 'J_0', besj1(x) t 'J_1', besjn(2, x) t 'J_2', besy0(x) t 'Y_0'
set key top left; set title 'gamma'
plot [-4:5] [-6:6] gamma(x) t '{/Symbol G}(x)', lgamma(x) t 'ln|{/Symbol G}(x)|'
set key top left; set title 'error and normal'
plot [-3:3] [-1.1:1.1] erf(x) t 'erf', norm(x) t 'norm', x >= 0 ? igamma(2, x) : 1/0 t 'igamma(2, x)'
set key top left; set title 'Lambert W, Airy'
plot [-2:5] lambertw(x) t 'W(x)', airy(x) t 'Ai(x)'
unset multiplotgnuplot's Bessel, gamma, error, normal, Lambert W and Airy functions, by its own algorithms: the values are gnuplot's. Γ is undefined at the poles, a gap. See Special functions.
Complex numbers
set terminal svg size 560,320; set output 'cb_complex.svg'
# a transfer function of complex values, {0,1} written I: its gain and its phase, as gnuplot plots them
A(w) = (I*w / (I*w + 100)) * (1 / (1 + I*w / 2e4))
set logscale x; set xrange [1:1e6]; set samples 400
set ylabel 'gain [dB]'; set y2label 'phase [deg]'
set ytics nomirror; set y2tics; set yrange [-45:5]; set y2range [-90:90]
set key bottom center
plot 20*log10(abs(A(x))) lw 2 title 'gain', 180/pi*arg(A(x)) axes x1y2 lw 2 title 'phase'Values are complex, as gnuplot's: I is {0,1} (or write {0,1}), abs and arg give the gain and the phase of a transfer function; a plotted value with an imaginary part is undefined. See Expressions.
A complex function over the plane
set terminal svg size 560,460; set output 'cb_complex_phase.svg'
# a complex function over the plane: the hue its phase, the saturation its magnitude (gnuplot's complex_trig demo)
set palette model HSV defined (0 0 1 1, 1 1 1 1)
set cbrange [-pi:pi]
set cbtics ("-π" -pi, "0" 0, "π" pi)
set cblabel 'phase'
hue(x, y) = (pi + atan2(-y, -x)) / (2*pi)
sat(z) = abs(z) > 1 ? 1 : abs(z)
color(x, y) = hsv2rgb(hue(real(f(x, y)), imag(f(x, y))), sat(f(x, y)), 1)
f(x, y) = atanh(x + y*{0,1})
set urange [-2:2]; set vrange [-2:2]; set xrange [-2:2]; set yrange [-2:2]
set view map; set size square; unset key
set isosamples 80, 80
set title 'atanh(x + iy)'
splot '++' using 1:2:(color(x, y)) with pm3d lc rgb variableatanh of a complex argument, as gnuplot 6.0 computes it (its branch cuts along the real axis beyond -1 and 1): the '++' pseudo-file samples the plane, x and y its variables, each point colored by hsv2rgb of the phase and the magnitude (lc rgb variable). asin, acos, atan, asinh, acosh and tanh take complex arguments too. See Expressions.
Labels and arrows in a loop
set terminal svg size 560,320; set output 'cb_set_for.svg'
# labels and arrows set in a loop (set for), the last label removed (unset for)
set for [i=1:5] label i sprintf('t_{%d}', i) at i, i**2 + 3 center
set for [i=1:5] arrow i from i, i**2 + 2.2 to i, i**2 + 0.4
unset for [i=5:5] label i
set xrange [0:6]; set yrange [0:32]; set key top left
plot x**2 lw 2 t 'x^2'set for [i=1:5] runs the set command once per value, unset for removes in a loop. See Iteration.
User variables and functions
set terminal svg size 560,320; set output 'cb_user_functions.svg'
A = 2.0; tau = 3.0; omega = 2*pi/2
envelope(t) = A*exp(-t/tau)
signal(t) = envelope(t)*cos(omega*t)
set xrange [0:2*tau]
plot signal(x) t 'signal', envelope(x) t 'envelope', -envelope(x) notitlename = value and name(t) = expression as in gnuplot: the functions read the variables when the plot is drawn, and the range ends take expressions. See User variables and functions.
A family of curves from arrays
set terminal svg size 560,320; set output 'cb_iterated_defs.svg'
# definitions before an iterated item run on each pass: a family of curves from two arrays
array rate[4] = [0.5, 1, 2, 4]
array shape[4] = [1, 1.3, 2, 3]
weibull(x, k, l) = 1 - exp(-(x/l)**k)
set xrange [0:5]; set key bottom right
plot for [i = 1:4] k = shape[i], l = 1.0/rate[i], weibull(x, k, l) lw 2 title sprintf("k = %.1f, rate %.1f", k, rate[i])Definitions written before an iterated item are run on each pass: for [i = 1:4] k = shape[i], l = 1.0/rate[i], weibull(x, k, l). See Iteration.
Names as in the formulas
set terminal svg size 560,320; set output 'cb_greek_names.svg'
# UTF-8 names: variables and functions written as the formulas are
ω = 2*pi; ζ = 0.15
y(τ) = exp(-ζ*ω*τ) * cos(ω*sqrt(1 - ζ**2)*τ)
set samples 300; set xrange [0:3]; set key top right
plot y(x) lw 2 t 'damped oscillation', exp(-ζ*ω*x) dt 2 t 'envelope'Names may hold UTF-8 letters, as gnuplot: ω, ζ, τ in variables, functions and their dummies. See User variables and functions.
Latin-1 strings and symbols
set terminal svg size 560,320; set output 'cb_latin1.svg'
# octal escapes write bytes; set encoding iso_8859_1 reads them as Latin-1; the Symbol font's upper half; \U+ code points
set encoding iso_8859_1
set label 1 "Temperatura: 21 \260C, caf\351" at graph 0.05, 0.88
set label 2 "{/Symbol \362}f(x) dx, x {/Symbol \256} {/Symbol \245}" at graph 0.05, 0.76
set label 3 "U+2192: a \U+2192 b" at graph 0.05, 0.64
plot [0:10] sin(x) / (x + 1) lw 2 title "sin(x)/(x+1)""\260" is an octal byte, as gnuplot; with set encoding iso_8859_1 the bytes read as Latin-1 (°, é), the Symbol font's upper half as its symbols (\362 the integral, \245 infinity), and \U+hhhh a code point in enhanced text. See Strings.
Sums and assignments in a plot
set terminal svg size 560,320; set output 'cb_sums.svg'
# partial sums of a Fourier series: sum [k=a:b] in a function, its order n set by assignments in the plot itself
square(x) = 4/pi * sum [k=1:n] sin((2*k - 1)*x) / (2*k - 1)
set samples 400
set xrange [-pi:pi]; set yrange [-1.6:1.6]
set key bottom right
plot n = 1, square(x) title 'n = 1', n = 3, square(x) title 'n = 3', n = 15, square(x) title 'n = 15'sum [k=a:b] term adds the term for each k (integers stay integers); a plot item may be an assignment, done in its turn, so each square(x) is drawn with the n set before it. See Expressions and Plot items.
Assignments inside expressions
set terminal svg size 560,320; set output 'cb_running_mean.svg'
# assignments inside expressions: shift5 moves a five-value window on each row, (s = s + $2, ...) a running sum
set samples 80
set table $D; plot [0:8] sin(x) + 0.4*sin(9*x); unset table
shift5(x) = (b5 = b4, b4 = b3, b3 = b2, b2 = b1, b1 = x)
avg5(x) = (shift5(x), (b1 + b2 + b3 + b4 + b5) / 5.)
set key bottom left
plot b1 = b2 = b3 = b4 = b5 = 0, s = 0, \
$D using 1:2 with points pt 7 ps 0.5 title 'data', \
'' using 1:(avg5($2)) with lines lw 2 title 'mean of the last 5', \
'' using 1:(s = s + $2, s / ($0 + 1)) with lines lw 2 title 'cumulative mean'name = value is an operator and (a, b) evaluates both, the last the value, as gnuplot: an expression of a using field runs on each row, so s sums along the file and shift5 keeps the last five values in b1 ... b5. See Expressions.
Array elements assigned in an expression
set terminal svg size 560,320; set output 'cb_array_assign.svg'
# array elements assigned inside an expression: stats stores each row of a datablock in A, then A is plotted
$DATA << EOD
1 3.2
2 4.1
3 2.7
4 5.0
5 3.9
EOD
stats $DATA using 1 nooutput
array A[STATS_records]
stats $DATA using (A[int($0 + 1)] = $2) nooutput
set key left; set yrange [0:6]; set xrange [0:6]
plot A using 1:2 with linespoints pt 7 title "A[i] filled by stats", \
A using 1:2:(sprintf("%.1f", $2)) with labels offset 0,1 notitleA[i] = value is an expression too: a stats or plot over a file stores each row in an element ($0 counts the rows from 0), and an expression that assigns elements of an array reads them as they are when it runs. See Arrays.
Recursive functions
set terminal svg size 560,320; set output 'cb_recursion.svg'
# Chebyshev polynomials by their recurrence: a recursive user function, as gnuplot 6.0
T(n, x) = n == 0 ? 1 : n == 1 ? x : 2*x*T(n - 1, x) - T(n - 2, x)
set xrange [-1:1]; set yrange [-1.2:1.2]; set samples 200
set title 'T_n(x) = 2x T_{n-1}(x) - T_{n-2}(x)'; set key outside right
plot for [n = 2:5] T(n, x) t sprintf('T_%d', n)The Chebyshev polynomials by their three-term recurrence: T(n, x) calls itself, as gnuplot 6.0 allows, 251 calls deep at most. See User variables and functions.
Function blocks
set terminal svg size 560,320; set output 'cb_function_blocks.svg'
# a function block: Newton's iterations for r**3 = a, with a local and a return from inside the loop
function $cbrt << EOF
local r = ARGV[1] > 1 ? 1.0 * ARGV[1] : 1.0
do for [k = 1:50] {
d = (r**3 - ARGV[1]) / (3*r**2)
r = r - d
if (abs(d) < 1e-12) { return r }
}
return r
EOF
set xrange [0:8]; set samples 60; set key top left
label = sprintf('$cbrt(27) = %g, $cbrt(2) = %.6f', $cbrt(27), $cbrt(2)); set title label
plot $cbrt(x) w lp pi 6 pt 7 t '$cbrt(x), Newton', x**(1./3) dt 2 lw 2 t 'x**(1./3)'A function block runs script lines when called: Newton's iterations in a loop, a local start, a return from inside the loop; $cbrt(x) is then plotted like any function. See Function blocks.
Bit flags
set terminal svg size 560,320; set output 'cb_bitwise.svg'
# solver status flags in one column, bit by bit: 1 converged step, 2 restart, 4 file written
$LOG << EOD
1 1.0e-1 0
2 3.2e-2 1
3 1.1e-2 1
4 2.5e-2 2
5 8.0e-3 1
6 2.4e-3 5
7 6.0e-3 2
8 1.6e-3 1
9 4.1e-4 5
10 1.0e-4 1
EOD
set logscale y; set format y '%.0e'; set xlabel 'step'; set key top right
plot $LOG u 1:2 w l t 'residual', \
$LOG u 1:(int($3) & 2 ? $2 : 1/0) w p pt 6 ps 2 t 'restart (bit 2)', \
$LOG u 1:(int($3) & 4 ? $2 : 1/0) w p pt 7 t 'file written (bit 4)'A status column packs flags as bits: int($3) & 2 keeps the restarts, int($3) & 4 the steps that wrote a file (a column is real, int makes it an integer for the bitwise operators). See Expressions in using.
Line styles and point types
set terminal svg size 560,320; set output 'cb_styles.svg'
set style line 1 lc rgb '#0072b2' lw 2
set style line 2 lc rgb '#e51e10' dt 2 pt 4
set logscale y
plot 'run.dat' u 1:2 ls 1 t 'continuity', '' u 1:3 every 6 w lp ls 2 t 'momentum'set style line N defines a style once; ls N applies it, the options after it override it.
Linetypes of your own
set terminal svg size 560,320; set output 'cb_linetype.svg'
# the linetypes redefined: every plot after it takes these colors, widths and points; the points larger
set linetype 1 lc "dark-violet" lw 2 pt 7
set linetype 2 lc "sea-green" lw 2 pt 9
set linetype 3 lc "dark-orange" lw 2 pt 5 dt 2
set pointsize 1.3; set key top left
plot [0:5] for [k = 1:3] x**(k/2.) w lp pi 8 t sprintf('x^{%d/2}', k)set linetype N redefines a linetype for every plot after it (reset keeps it); set pointsize sets the size of the points without their own. See Styles.
Point and dash types
set terminal svg size 640,300; set output 'cb_point_types.svg'
# the point types 0..15 (pt) and dash types 1..5 (dt): a reference chart
$ROW << EOD
0 1
EOD
set xrange [-0.5:15.5]; set yrange [-6:2]; unset ytics; set xtics 1; set key off
set title 'point types (pt 0 to 15) and dash types (dt 1 to 5)'
plot for [i = 0:15] $ROW u (i):2 w p pt i ps 2 notitle, \
for [d = 1:5] -d dt d lw 2 notitleThe 16 point types (pt 0 a dot, odd ones from 5 filled) and the 5 dash types, for picking one; a one-line datablock gives the point its place, plot for repeats it.
Interrupted lines
set terminal svg size 560,320; set output 'cb_interrupted_lines.svg'
# pointinterval -N: a marker every N points, the line blanked under it
set samples 60; set xrange [0:3]; set key top right
plot cos(x) lt -1 pi -4 pt 6 with linespoints t 'pi -4', cos(x - 0.4) lt -1 pi -5 pt 4 with linespoints t 'pi -5', \
cos(x - 0.8) lt -1 pi 6 pt 7 with linespoints t 'pi 6'pointinterval -N (pi -N) marks every N-th point and blanks the line under the marker; pi N only marks. lt -1 is solid black, whatever the dash type of the item's own linetype. See plot items.
Characters as points
set terminal svg size 560,320; set output 'cb_char_points.svg'
# a character as the point (pt "c"), in its tc color, every 4 points (pi) or about 8 of them (pn)
set encoding utf8
set samples 41; set xrange [0:2*pi]; set key bottom left
plot '+' using 1:(sin(x)) with linespoints pt "◆" pi 4 tc rgb '#d55e00' lw 2 title 'pt "◆" pi 4', \
'+' using 1:(cos(x)) with linespoints pt "x" pn 8 lw 2 title 'pt "x" pn 8'pt "c" draws a character as the point, in the item's tc color; pi N marks every N-th point, pn N about N evenly spread. See Point types.
Dash patterns of your own
set terminal svg size 560,320; set output 'cb_dashes.svg'
# custom dash types: a dash string of . - _ and blanks, or the lengths (solid, empty, ...); lc bgnd hides a line
set yrange [0:6]; set key outside right
plot 1 lw 2 dt "-" title 'dt "-"', 2 lw 2 dt "." title 'dt "."', 3 lw 2 dt "._" title 'dt "._"', \
4 lw 2 dt "..- " title 'dt "..- "', 5 lw 2 dt (20,5,2,5) title 'dt (20,5,2,5)'dt "string" draws gnuplot's custom patterns: . a dot, - a dash, _ a long dash, a blank a longer gap; dt (solid, empty, ...) gives the lengths; both scale with the line width. lc bgnd, lt nodraw and lt -1 are the background, nothing and black. See Line properties.
A color per point
set terminal svg size 560,320; set output 'cb_lc_variable.svg'
set key top left
plot 'classes.dat' u 1:2:3 w p pt 7 ps 1.5 lc variable t 'runs, colored by class', \
'' u 1:2:(1+($2 > 3)) w l lc variable t 'segments above 3 in green'lc variable reads the color of each point from the last using column, a linetype number; a segment takes the color of its end point, as in gnuplot. lc rgb variable reads 24-bit colors instead (0xRRGGBB). See Colors per point.
A type, size and color per point
set terminal svg size 560,360; set output 'cb_pt_variable.svg'
# points whose type, size and color come from columns (pt variable, ps variable, lc rgb variable)
$SITES << EOD
# x y size type color
1.0 2.0 1.5 7 0x1b9e77
2.2 3.1 2.5 5 0xd95f02
3.1 1.4 1.0 9 0x7570b3
4.0 2.6 3.0 7 0xe7298a
5.2 3.4 2.0 13 0x66a61e
5.8 1.8 1.5 5 0xe6ab02
EOD
set xrange [0:7]; set yrange [0:4.5]
set key top left
plot $SITES using 1:2:3:4:5 with points ps variable pt variable lc rgb variable title 'sites'pt variable reads each point's type from a column, after the sizes of ps variable and before the colors of lc rgb variable: using x:y:size:type:color. The key sample of such an item is a dot, as gnuplot's. See Point types.
High values on top
set terminal svg size 560,320; set output 'cb_zsort.svg'
# zsort: the points drawn in the order of their z, the high values on top
set print $D
do for [i=1:3000] { print rand(0), rand(0), invnorm(rand(0)) }
unset print
set palette cubehelix negative; set cbrange [-3:3]; unset key
set multiplot layout 1,2
set title "file order"
plot $D using 1:2:3 with points pt 7 ps 0.5 lc palette
set title "zsort"
plot $D using 1:2:3:3 zsort with points pt 7 ps 0.5 lc palette
unset multiplotzsort draws the points of a curve in the order of their z (the third column), the highest last, so dense clouds show their extremes, as gnuplot 6.0. See plot items.
Colors from the palette
set terminal svg size 560,320; set output 'cb_lc_palette.svg'
set datafile separator comma # run.csv: iteration, continuity, momentum, energy, cd, dcd
set palette viridis; set cblabel 'iteration'
set logscale y; set xlabel 'cd'; set ylabel 'residual'
# the path of the run in (cd, residual), colored by the iteration; a second residual in one palette color
plot 'run.csv' u 5:2:1 w lp pt 7 ps 0.6 lc palette z t 'continuity', \
'' u 5:3 w l lw 2 lc palette frac 0.9 t 'momentum'lc palette z colors each point by the last using column through the palette: here the iteration, so the path of the run reads from dark to light, and the color box gives the scale. lc palette frac F takes one color of the palette for a whole item. See Colors per point.
Color sequences
set terminal svg size 760,320; set output 'cb_colorsequence.svg'
set multiplot layout 1,2
set key off; set xrange [0:6]
set title 'set colorsequence podo'; set colorsequence podo
plot sin(x), sin(x+1)+1, sin(x+2)+2, sin(x+3)+3, sin(x+4)+4, sin(x+5)+5
set title 'set colorsequence batlowS 6'; set colorsequence batlowS 6
plot sin(x), sin(x+1)+1, sin(x+2)+2, sin(x+3)+3, sin(x+4)+4, sin(x+5)+5
unset multiplotset colorsequence default|podo|classic picks gnuplot's linetype colors; foresight's set colorsequence batlowS 6 takes the first colors of a categorical order of the Scientific colour maps, the most distinct first. See Styles.
Error bars
set terminal svg size 560,320; set output 'cb_errorbars.svg'
plot 'run.dat' using 1:5:6 every 5 with yerrorbars pt 7 ps 0.6 title 'cd'x:y:dy, or x:y:low:high; the caps keep their size under zoom.
Error bar caps
set terminal svg size 760,280; set output 'cb_errorbar_caps.svg'
# the error bar caps: the default, longer and red, none
set multiplot layout 1,3
set logscale x; set key off; set xrange [5e3:2e6]
set title 'default'
plot 'measures.dat' u 1:2:4 w yerrorbars pt 7
set title "set errorbars 3 lc 'red' lw 2"; set errorbars 3 lc rgb 'red' lw 2
plot 'measures.dat' u 1:2:4 w yerrorbars pt 7
set title 'set errorbars small'; set errorbars small
plot 'measures.dat' u 1:2:4 w yerrorbars pt 7
unset multiplotset errorbars 3 makes the caps three times the default, lc and lw draw the bars in their own line, small drops the caps. See Error bar caps.
Error bars on both axes
set terminal svg size 560,320; set output 'cb_xyerrorbars.svg'
set logscale x
set xlabel 'Re'; set ylabel 'cd'
plot 'measures.dat' using 1:2:3:4 with xyerrorbars pt 7 title 'wind tunnel'with xyerrorbars takes x:y:dx:dy, or x:y:xlow:xhigh:ylow:yhigh.
Lines through error bars
set terminal svg size 560,320; set output 'cb_errorlines.svg'
set logscale x; set xlabel 'Re'; set ylabel 'cd'
plot 'measures.dat' u 1:2:4 w yerrorlines pt 7 t 'yerrorlines', \
'' u 1:($2+0.1):3:4 w xyerrorlines pt 5 t 'xyerrorlines'yerrorlines and xyerrorlines are linespoints with the error bars of the matching errorbars style and the same using layouts. See Lines, steps and impulses.
Steps
set terminal svg size 560,320; set output 'cb_steps.svg'
set xlabel 'iteration'; set ylabel 'dt [ms]'; set key bottom right
plot 'timestep.dat' u 1:2 w steps lw 2 t 'steps', '' u 1:2 w fsteps t 'fsteps', '' u 1:($2+1) w histeps t 'histeps + 1'steps goes horizontally then vertically, fsteps the other way round, histeps draws a step around each point (edges halfway to the neighbours) from and back to 0. An adaptive time step reads best as steps.
Filled steps
set terminal svg size 560,320; set output 'cb_fillsteps.svg'
# fillsteps: the area under steps, filled to y = 0 in the fill style
set style fill solid 0.5
set samples 30
set table $H; plot [0:15] 6*exp(-(x - 6)**2 / 10) + 1; unset table
set yrange [0:8]
plot $H using 1:2 with fillsteps lc rgb '#56b4e9' title 'fillsteps', \
'' using 1:2 with steps lw 2 lc rgb '#0072b2' title 'steps'with fillsteps fills the area under the steps down to y = 0 in the fill style, as gnuplot. See Lines, steps and impulses.
A spectrum: impulses and dots
set terminal svg size 560,320; set output 'cb_impulses.svg'
set xlabel 'frequency [Hz]'; set ylabel 'amplitude'
plot 'spectrum.dat' u 1:2 w impulses lw 3 t 'impulses', '' u 1:($2+0.05) w dots t 'dots'impulses draws a segment from y = 0 to each point (0 is in the autoscale, as gnuplot); dots a tiny dot per point.
Functions of x
set terminal svg size 560,320; set output 'cb_function.svg'
set samples 400
plot sin(x)/x title 'sinc', exp(-abs(x)/4) dt 2Without data, functions are sampled over [-10:10], or the xrange; set samples sets the number of points.
Sharp extrema of a function
set terminal svg size 560,320; set output 'cb_sharpen.svg'
# sharpen: the extrema of a function between its samples found and added
set samples 150; set xrange [-8:8]; set yrange [-0.1:1.2]; set key bottom right
plot abs(sqrt(sin(x))) + 0.15 title "sampled", abs(sqrt(sin(x))) sharpen title "sharpen"sharpen finds the extrema of a function that fall between its samples (a golden section search where the curve turns) and adds them: the minima of abs(sqrt(sin(x))) reach 0, while the plain samples stop short. See Functions.
Parametric curves
set terminal svg size 560,360; set output 'cb_parametric.svg'
# parametric curves: x(t), y(t) over trange, a Lissajous figure and an epicycloid
set parametric; set trange [0:2*pi]; set samples 400
set size ratio 1; set xrange [-1.6:1.6]; set yrange [-1.6:1.6]; set key outside right
plot sin(3*t), cos(2*t) lw 2 t 'Lissajous 3:2', \
1.2*cos(t) - 0.3*cos(4*t), 1.2*sin(t) - 0.3*sin(4*t) lw 2 t 'epicycloid'set parametric reads each function item as a pair x(t), y(t), sampled over trange. See Parametric plots.
Sampled pseudo-files
set terminal svg size 560,400; set output 'cb_sampled.svg'
# the '+' and '++' pseudo-files: sampled variables through using, a field of vectors and a sampled ellipse
set urange [-2:2]; set vrange [-2:2]; set samples 11; set isosamples 11
set xrange [-2.5:2.5]; set yrange [-2.5:2.5]; set size ratio 1
plot '++' using 1:2:($2*0.15):(-$1*0.15):(sqrt($1**2 + $2**2)) with vectors filled lc palette z notitle, \
[t=0:2*pi:pi/20] '+' using (2*cos(t)):(1.2*sin(t)) with lines lw 2 title "[t=0:2π] '+'"The pseudo-file '+' samples a variable as its column 1, here t over the item's own range by pi/20; '++' is a grid of u and v (set samples, set isosamples points over urange, vrange), the columns of a vector field colored by its length. See Sampled pseudo-files.
Asymptotes and clipping
set terminal svg size 560,320; set output 'cb_clip.svg'
# clipping: by default, as gnuplot, a segment with both ends out of the plot is not drawn (no line down the asymptotes)
set multiplot layout 1,2
set yrange [-4:4]; set samples 60; set title 'default (unset clip two)'
plot [-2*pi:2*pi] tan(x) notitle
set clip two; set title 'set clip two'
replot
unset multiplotAs gnuplot, a segment with both ends out of the plot is not drawn: no line down the asymptotes; set clip two draws it. See Clipping.
A range for one plot
set terminal svg size 560,320; set output 'cb_inline_range.svg'
plot [t=0:4*pi] [-1.2:1.2] sin(t) t 'sin(t)', exp(-t/6)*cos(t) t 'damped'Inline ranges set x, then y, for that plot only: set xrange is left alone. t= names the variable of the functions.
A model over the data
set terminal svg size 560,320; set output 'cb_model.svg'
# the function is sampled over the x range of the data
plot 'run.dat' u 1:5 with points pt 6 t 'cd', 0.30 + 0.25*exp(-x/25)*cos(x/6) t 'model'A function is sampled over the x range of the data of the same plot.
One line per column
set terminal svg size 560,320; set output 'cb_plot_for.svg'
# one line per residual column, its title a word of a string
names = 'continuity momentum energy'
set logscale y; set format y '%.0e'; set xlabel 'iteration'; set ylabel 'residual'
plot for [i=2:4] 'run.dat' u 1:i w l lw 2 t word(names, i-1)plot for plots the item once per value of i: u 1:i reads column i, word(names, i-1) titles it, the colors advance as for separate items.
Statistics of a run
set terminal svg size 560,320; set output 'cb_stats.svg'
# the drag coefficient once settled: statistics of the iterations from 80 on (the others invalid), the report printed
stats 'run.dat' u ($1 >= 80 ? $5 : 1/0) name 'cd' output
set xlabel 'iteration'; set ylabel 'cd'; set key bottom right
plot 'run.dat' u 1:5 w l lw 2 t 'cd', \
cd_mean w l dt 2 lc 'black' t sprintf('mean %.4f +- %.4f', cd_mean, cd_stddev)$ foresight cb_stats.gp
* FILE:
Records: 41
Out of range: 0
Invalid: 79
Header records: 0
Blank: 1
Data Blocks: 1
* COLUMN:
Mean: 0.2996
Std Dev: 0.0035
Sample StdDev: 0.0036
Skewness: -0.0909
Kurtosis: 2.0367
Avg Dev: 0.0031
Sum: 12.2836
Sum Sq.: 3.6807
Mean Err.: 0.0005
Std Dev Err.: 0.0004
Skewness Err.: 0.3825
Kurtosis Err.: 0.7651
Minimum: 0.2941 [13]
Maximum: 0.3073 [ 0]
Quartile: 0.2963
Median: 0.3008
Quartile: 0.3024
foresight: cb_stats.svgstats sets cd_mean, cd_stddev and the other cd_* values of the iterations kept (the condition makes the others invalid); output prints gnuplot's report, silent otherwise. The mean is then a constant to plot, and sprintf writes it in the title.
A summary in the terminal
# a summary of the run in the terminal: a loop over the columns, stats and sprintf
names = 'continuity momentum energy'
print sprintf('%-11s %10s %10s %7s', 'residual', 'max', 'min', 'orders')
do for [i = 2:4] {
stats 'run.dat' u i name 'r' nooutput
print sprintf('%-11s %10.3e %10.3e %7.1f', word(names, i - 1), r_max, r_min, log10(r_max/r_min))
}$ foresight cb_loops.gp
residual max min orders
continuity 1.005e+00 5.019e-06 5.3
momentum 4.510e-01 6.553e-06 4.8
energy 1.778e+00 1.995e-06 6.0do for runs the block per column, stats (silent with nooutput, as in gnuplot) measures it, print and sprintf write the table: a report at the end of a run, without a plot.
Fitting a model
set terminal svg size 560,320; set output 'cb_fit.svg'
# the observed order of accuracy: fit error = c h^p, the report on the terminal
f(h) = c*h**p
c = 1; p = 1
set fit results
fit f(x) 'convergence.dat' using 1:2 via c, p
set logscale xy; set format y '%.0e'
set xlabel 'mesh size h'; set ylabel 'error'; set key top left
plot 'convergence.dat' w p pt 7 ps 1.2 t 'measured', f(x) lw 2 t sprintf('fit c h^p, p = %.2f', p)$ foresight cb_fit.gp
After 9 iterations the fit converged.
final sum of squares of residuals : 1.80725e-11
rel. change during last iteration : -5.36663e-11
degrees of freedom (FIT_NDF) : 3
rms of residuals (FIT_STDFIT) = sqrt(WSSR/ndf) : 2.45442e-06
variance of residuals (reduced chisquare) = WSSR/ndf : 6.02417e-12
Final set of parameters Asymptotic Standard Error
======================= ==========================
c = 0.20607 +/- 0.002962 (1.438%)
p = 1.99174 +/- 0.006114 (0.307%)
correlation matrix of the fit parameters:
c p
c 1.000
p 0.997 1.000
foresight: cb_fit.svgfit adjusts the parameters after via (user variables; an undefined one starts at 1) by gnuplot's Marquardt-Levenberg method, to gnuplot's digits, and sets c_err, p_err and the FIT_* variables. It is silent unless asked: set fit results prints gnuplot's report, set fit logfile 'fit.log' appends it to a file. Here the slope p is the observed order of accuracy of a scheme. From Fortran, call fit(model, x, y, params) does the same (library).
A fit with errors in x and y
set terminal svg size 560,360; set output 'cb_fit_xyerrors.svg'
# Pearson's data with York's weights: a straight line fitted three ways (gnuplot's fit.dem)
$PY << EOD
0.0 1000 5.9 1.0
0.9 1000 5.4 1.8
1.8 500 4.4 4.0
2.6 800 4.6 8.0
3.3 200 3.5 20.0
4.4 80 3.7 20.0
5.2 60 2.8 70.0
6.1 20 2.8 70.0
6.5 1.8 2.4 100.0
7.4 1.0 1.5 500.0
EOD
f(x) = a + b*x; a = 5; b = -0.5
fy(x) = ay + by*x; ay = 5; by = -0.5
fxy(x) = axy + bxy*x; axy = 5; bxy = -0.5
fit f(x) $PY using 1:3 via a, b # no errors
fit fy(x) $PY using 1:3:(sqrt(1./$4)) yerrors via ay, by # errors of y
fit fxy(x) $PY using 1:3:(sqrt(1./$2)):(sqrt(1./$4)) xyerrors via axy, bxy # errors of x and y
set key bottom left
set title "one line, three fits"
plot $PY using 1:3:(sqrt(1./$2)):(sqrt(1./$4)) with xyerrorbars lt -1 title 'data', \
f(x) lw 2 title sprintf('no errors: %.3f %+.3f x', a, b), \
fy(x) lw 2 title sprintf('yerrors: %.3f %+.3f x', ay, by), \
fxy(x) lw 2 title sprintf('xyerrors: %.3f %+.3f x', axy, bxy)Pearson's data with York's weights, a classic test of straight line fits: yerrors weighs each point by its y error, xyerrors by its effective error, the y error combined with the x error times the slope of the model (Orear's effective variance, gnuplot's). See Fit.
A fit of two variables
set terminal svg size 560,320; set output 'cb_fit_surface.svg'
# fit of two independent variables: using x:y:z:s, the function of x and y
$GRID << EOD
1 1 3.1
1 2 5.0
2 1 4.1
2 2 6.0
3 1 4.9
3 2 7.1
3 3 9.0
EOD
plane(x, y) = a*x + b*y + c
a = 1; b = 1; c = 0.5
fit plane(x, y) $GRID using 1:2:3:(1) via a, b, c
print sprintf('a = %.3f, b = %.3f, c = %.3f', a, b, c)
set xlabel 'x'; set ylabel 'z'; set key top left
plot for [k = 1:3] $GRID using 1:($2 == k ? $3 : NaN) with points pt 7 ps 1.4 lc k t sprintf('y = %d', k), \
for [k = 1:3] plane(x, k) lw 2 lc k notitle$ foresight cb_fit_surface.gp
a = 0.974, b = 1.997, c = 0.089
foresight: cb_fit_surface.svgfit takes a function of x and y: using x:y:z:s, the last column the errors (here 1, unweighted). The fitted plane is drawn at each y as a line. See Fit.
Histogram and distribution
set terminal svg size 560,320; set output 'cb_smooth.svg'
set datafile separator comma # run.csv: the whole history in one block (run.dat breaks it at the restart)
set xlabel 'cd'; set ylabel 'iterations'; set y2label 'fraction'; set y2tics; set key top left
# bins 0.02 wide: frequency sums the 1 of each point in a bin
plot 'run.csv' u (floor($5/0.02)*0.02):(1) smooth frequency w lp pt 7 t 'histogram', \
'' u 5:(1) smooth cnormal axes x1y2 t 'distribution'smooth frequency sums the y of the points of equal x: binned x and y = 1 count the points per bin (bins does the binning itself: a histogram of a sample). smooth cnormal accumulates them over the sorted x, divided by the total: the fraction of iterations below each value. smooth unique averages repeated x instead. See Smoothing.
Block averages and running totals
set terminal svg size 760,320; set output 'cb_unique.svg'
set multiplot layout 1,2
set xlabel 'step'; set ylabel 'wall time [s]'; set key top left
# the mean of the steps of each block of 25 (repeated x merged): unique
plot 'steptimes.dat' u 1:2 w p pt 7 ps 0.4 t 'per step', \
'' u (floor(($1-1)/25)*25+13):2 smooth unique w lp lw 2 pt 7 t 'mean of 25 steps'
set ylabel 'elapsed [s]'
# the running total: cumulative
plot 'steptimes.dat' u 1:2 smooth cumulative lw 2 t 'elapsed time'
unset multiplotsmooth unique merges the points of equal x into their mean: an x rounded to blocks of 25 steps gives the mean wall time of each block. smooth cumulative adds the y up to each x: the elapsed time of the run. See Smoothing.
Splines and densities
set terminal svg size 760,320; set output 'cb_splines.svg'
set multiplot layout 1,2
set samples 200
set key bottom left
plot 'noisy.dat' u 1:2 w p pt 7 t 'signal', \
'' u 1:2 smooth csplines t 'csplines', \
'' u 1:2:(2) smooth acsplines t 'acsplines', \
'' u 1:2 smooth sbezier t 'sbezier'
set key top right
set xrange [-2:6]
plot 'noisy.dat' u 3:(1) smooth kdensity t 'kdensity', \
'' u 3:(1) smooth kdensity bandwidth 0.15 t 'bandwidth 0.15'
unset multiplotcsplines passes through every point; acsplines weighs fit against smoothness (smaller weights, smoother curve); sbezier stays inside the points. kdensity estimates the distribution of a sample: gnuplot's bandwidth by default, narrower to show more detail.
A spline along a path
set terminal svg size 560,360; set output 'cb_smooth_path.svg'
# smooth path: a spline along each set of points in their order, closed with filledcurves
$CURVES << EOD
1 2
1.5 2
2 2.5
3 5
2.5 5
1.5 4
3 3
3.5 3.1
3.7 3.2
3.6 3.7
3.5 4.0
3.2 3.5
3 3
EOD
set xrange [0:5]; set yrange [1:6]; set key top right
set style fill transparent solid 0.25 border
plot $CURVES using 1:2 smooth path with filledcurves closed title "smooth path", \
$CURVES using 1:2 with points pt 7 lc "#0072b2" title "points"smooth path fits each set of points (apart at blank lines) in its order, not sorted on x: a closed set wraps around, and with filledcurves closed closes every set. See Smoothing.
Hulls around scattered points
set terminal svg size 560,360; set output 'cb_hulls.svg'
# convexhull, concavehull (a chi-shape) and expand D: curves bounding scattered points
set print $P
do for [i=1:80] {
print sprintf("%.4f %.4f", 3*invnorm(rand(0)) + (i % 2)*6, 2*invnorm(rand(0)))
}
unset print
set key outside right; set size ratio -1
plot $P with points pt 7 ps 0.5 lc "gray" title "points", \
$P convexhull with lines lw 2 title "convexhull", \
$P concavehull with lines lw 2 title "concavehull", \
$P convexhull expand 1 smooth path with lines dt 2 title "expand 1 smooth path"convexhull keeps the points of the bounding convex polygon, clockwise and closed; concavehull a chi-shape that follows the hollows (its length from the variable chi_length, else set chi_shape fraction of the longest edge); expand D pushes the hull out by D, and smooth path rounds it. As gnuplot 6.0, point for point. See Smoothing.
A monotone interpolation
set terminal svg size 560,320; set output 'cb_mcsplines.svg'
set xlabel 'iteration'; set ylabel 'dt [ms]'; set key top left
set yrange [0:5]
plot 'timestep.dat' w p pt 7 t 'time step', \
'' smooth csplines dt 2 t 'csplines', \
'' smooth mcsplines lw 2 t 'mcsplines'The natural spline (csplines) swings above and below each plateau of the time step; the monotone spline of Fritsch and Carlson (mcsplines) passes through the same points and never beyond them: a step stays a step, a positive quantity stays positive. See Smoothing.
Bars and statistics
A bar chart
set terminal svg size 560,320; set output 'cb_boxes.svg'
set style fill solid 0.5
set boxwidth 0.8 relative
plot 'run.dat' every 10 u 1:5 w boxes t 'cd every 10 iterations'Boxes stand on y = 0 and the autoscale reaches 0 and the box edges, unlike gnuplot: bar lengths are proportional to the values. See Boxes and filled curves.
A histogram of a sample
set terminal svg size 560,320; set output 'cb_bins.svg'
set style fill solid 0.4 border
set xlabel 'wall time per step [s]'; set ylabel 'steps'
# one column: x, each step counting 1; kdensity weighted by the bin width, on the same scale
plot 'steptimes.dat' u 2 bins binwidth=0.02 with boxes t 'bins, 0.02 s wide', \
'' u 2:(0.02) smooth kdensity lw 2 t 'kdensity'bins counts the values of one column in bins of equal width: here 0.02 s, as few bins as cover the data. Boxes touch, and the autoscale reaches the outer bin edges and 0. The kernel density of the same column, each point weighted by the bin width, lands on the same scale. See Bins.
Grouped bars with category labels
set terminal svg size 560,320; set output 'cb_histograms.svg'
set style fill solid 0.6 border -1
plot 'timings.dat' u 2:xtic(1) w histograms t 'mesh', '' u 3 w hist t 'fluxes', '' u 4 w hist t 'comm'xtic(1) labels each row with the text of column 1; the labels replace the x ticks.
Stacked bars
set terminal svg size 560,320; set output 'cb_rowstacked.svg'
set style fill solid 0.6 border -1
set style histogram rowstacked; set boxwidth 0.6
plot 'timings.dat' u 2:xtic(1) w histograms t 'mesh', '' u 3 w hist t 'fluxes', '' u 4 w hist t 'comm'rowstacked piles the items of a row on one bar; set boxwidth 0.6 leaves room between the stacks. See Histograms.
Bars with error bars
set terminal svg size 560,320; set output 'cb_boxerrorbars.svg'
set style fill solid 0.4; set boxwidth 0.6
set ylabel 'seconds per step'
plot 'bench.dat' u 1:2:3:xtic(4) w boxerrorbars t 'mean +/- std of 20 runs'boxerrorbars is boxes with the y error bars: x:y:ydelta, x:y:ydelta:width or x:y:ylow:yhigh:width; xtic(4) names the bars. See Box, finance and boxplot styles.
Groups of bars
set terminal svg size 560,320; set output 'cb_hist_groups.svg'
# two groups of bars from two files, titled below the axis, the second from linetype 3
set style data histograms
set style fill solid 0.7 border -1; set style histogram clustered gap 1
set ylabel 'wall time per step [s]'
plot newhistogram 'mesh and fluxes', 'timings.dat' u 2:xtic(1) t 'mesh', '' u 3 t 'fluxes', \
newhistogram 'comm' lt 3, '' u 4:xtic(1) t 'comm'newhistogram starts a group 2 rows after the previous one, its title below the axis, its colors from lt 3.
Group titles
set terminal svg size 560,320; set output 'cb_hist_titles.svg'
# group titles in a color, moved down half a line
set style data histograms; set style fill solid 0.7 border -1
set style histogram clustered gap 1 title tc rgb '#b3163f' offset 0,-0.5
set key top left; set ylabel 'wall time [s]'
plot newhistogram 'mesh', 'timings.dat' u 2:xtic(1) t 'mesh', \
newhistogram 'fluxes', '' u 3:xtic(1) t 'fluxes'set style histogram ... title tc C offset X,Y colors the group titles and moves them (in characters).
One stack per column
set terminal svg size 560,320; set output 'cb_hist_columns.svg'
# one stack per build (the column headers below them), each phase in its color, named in the key
set style data histograms
set style fill solid 0.8 border -1; set style histogram columnstacked
set ylabel 'share of the step [%]'; set key outside right
plot 'shares.dat' u 2 t columnhead, '' u 3 t columnhead, '' u 4:key(1) t columnheadcolumnstacked stacks each column: the rows in their linetype colors, named in the key by key(1), the stacks named by the column headers (title columnhead).
Stacks colored by category
set terminal svg size 560,320; set output 'cb_hist_colors.svg'
# column-stacked histograms colored by category (lc variable), each stack named by its title
$RUN1 << EOD
mesh 3
solve 12
io 2
EOD
$RUN2 << EOD
mesh 2
solve 8
io 4
EOD
set style data histogram; set style histogram columns; set style fill solid border lc "black"; set boxwidth 0.6
names = "mesh solve io"
set linetype 101 lc "steelblue"; set linetype 102 lc "dark-orange"; set linetype 103 lc "sea-green"
color(name) = 100 + (name eq "mesh" ? 1 : name eq "solve" ? 2 : 3)
set key outside right title "phase"
plot for [run in "$RUN1 $RUN2"] run using 2:(color(strcol(1))) lc variable title run, \
for [i=1:3] keyentry with boxes lc (100 + i) title word(names, i)Column-stacked histograms take lc variable: each row in the linetype a function of its category gives; the stacks are named by their titles and keyentry builds the key. See Histograms.
Clustered bars with error bars
set terminal svg size 560,320; set output 'cb_hist_errorbars.svg'
# the mean and the spread of each phase: errorbars histograms, using Y:ERR
set style data histograms
set style fill solid 0.6 border -1; set style histogram errorbars gap 1 lw 2
set yrange [0:*]; set ylabel 'wall time per step [s]'
plot 'timings.dat' u 2:($2*0.1):xtic(1) t 'mesh', '' u 3:($3*0.15) t 'fluxes', '' u 4:($4*0.3) t 'comm'errorbars lays the bars out as clustered and draws the error of each (using Y:ERR, or Y:LOW:HIGH), lw 2 wide.
Pattern fills
set terminal svg size 560,320; set output 'cb_patterns.svg'
set style fill pattern 4 border; set key top left
plot 'timings.dat' u 2:xtic(1) w hist t 'mesh', '' u 3 w hist t 'fluxes', '' u 4 w hist t 'comm'set style fill pattern N hatches the filled items, the pattern cycling from N item after item as in gnuplot: the 8 patterns of its svg terminal (0 empty, 1 and 2 crosshatches, 3 solid, 4 to 7 hatches), for prints without color.
Candlesticks and finance bars
set terminal svg size 560,320; set output 'cb_candlesticks.svg'
set boxwidth 20; set xlabel 'iteration'; set ylabel 'log10 residual'
plot 'windows.dat' u 1:2:3:4:5 w candlesticks t 'candlesticks' whiskerbars 0.5, \
'' u ($1+20):2:3:4:5 w financebars t 'financebars'candlesticks take x:open:low:high:close (here the first, smallest, largest and last residual of each window of 50 iterations): a box between open and close, whiskers to low and high, whiskerbars 0.5 crossbars. With an empty fill a falling candle (close below open) is filled, as gnuplot: a converging run fills them all. financebars draw the same as a line with an open tick on the left and a close tick on the right.
Candles colored by a column
set terminal svg size 560,320; set output 'cb_lc_styles.svg'
# lc variable on candlesticks: the last column picks the linetype, 2 (green) up, 7 (red) down
$P << EOD
1 10 8 14 12 2
2 12 11 16 15 2
3 15 12 17 13 7
4 13 9 14 10 7
5 10 7 12 11 2
EOD
set boxwidth 0.4; set style fill solid 0.7 border lc 'black'
set xrange [0:6]; set yrange [5:19]
plot $P using 1:2:3:4:5:6 with candlesticks lc variable title 'open, low, high, close'lc variable takes the linetype of each candle from the last using column: here 2 (green) when the price closes up, 7 (red) when down. It also colors histograms, boxxyerror rectangles, filled curves and polygons. See Colors.
A swarm of points
set terminal svg size 560,320; set output 'cb_jitter.svg'
# a swarm plot: overlapping values of three groups spread out (set jitter)
set print $SCORES
do for [g = 1:3] { do for [i = 1:40] { print g, round(5*g + 3 + 2*invnorm(rand(0))) } }
set print
set jitter overlap 1 spread 0.6
set xrange [0.3:3.7]; set xtics ("A" 1, "B" 2, "C" 3); set ylabel 'score'
plot $SCORES u 1:2:1 w p pt 7 ps 0.7 lc variable notitleset jitter moves the points that would overlap aside, alternately left and right: a bee swarm. The values are drawn with gnuplot's invnorm(rand(0)). See Point types.
Box plots by category
set terminal svg size 560,320; set output 'cb_boxplot.svg'
set style fill solid 0.3; set ylabel 'wall time per step [s]'
plot 'walltime.dat' u (1):2:(0.5):1 w boxplot t '12 runs per solver'boxplot summarizes the values of its item: quartiles, median, whiskers to the farthest values within 1.5 interquartile ranges, the others as outliers. The 4th using field is a factor column: one box per solver, named on the x axis. set style boxplot sets the whisker range, outliers, sorting.
Areas and shapes
A band around a curve
set terminal svg size 560,320; set output 'cb_filledcurves.svg'
plot 'run.dat' u 1:($5-$6):($5+$6) w filledcurves fs transparent solid 0.3 t 'cd +/- dcd', \
'' u 1:5 w l t 'cd'x:y1:y2 fills between two columns; filledcurves y=0 fills down to a line.
A smoothed band
set terminal svg size 560,320; set output 'cb_smooth_band.svg'
# a band x:y1:y2 smoothed (both curves by the filter, on the same samples), the fields read by a format string
$ENVELOPE << EOD
0 0.2 1.0
1 0.6 1.6
2 0.5 1.9
3 1.1 2.2
4 0.9 2.6
5 1.5 2.4
EOD
set samples 100; set key top left
plot $ENVELOPE using 1:2:3 "%lf %lf %lf" smooth csplines with filledcurves fs transparent solid 0.4 t 'smoothed band', \
$ENVELOPE using 1:2:3 with filledcurves fs transparent solid 0.2 t 'raw band'A band x:y1:y2 of filledcurves takes the curve filters: smooth csplines smooths both curves on the same samples. The format string after using reads the fields by scanf conversions, as gnuplot. See Boxes and filled curves.
A transparent fill color
set terminal svg size 560,320; set output 'cb_fill_color.svg'
# fc: the fill's own color, here transparent (#AARRGGBB), the line keeping lc; rgb reads a string variable
set samples 80
set table $E; plot [0:10] exp(-x / 4) * sin(2*x); unset table
Shade = '#80e0a080'
plot $E using 1:($2 + 0.15):($2 - 0.15) with filledcurves fc rgb Shade title 'error band', \
'' using 1:2 with lines lw 2 lc rgb '#b03030' title 'model'fc is the fill's own color, here gnuplot's #AARRGGBB with an alpha channel, read from a string variable after rgb; the line keeps lc. See Plot items.
Fill above and below a line
set terminal svg size 560,320; set output 'cb_fill_above.svg'
set style fill solid 0.35; set xlabel 'iteration'; set ylabel 'cd'
plot 'run.dat' u 1:5 w filledcurves above y=0.35 t 'above 0.35', \
'' u 1:5 w filledcurves below y=0.35 t 'below 0.35', \
'' u 1:5 w l lc 'black' t 'cd'filledcurves above y=V and below y=V keep the parts of the area to the line where the curve is above or below it; x1 and x2 fill to the bottom and top of the plot, xy=X,Y to a point. The restart at iteration 60 splits the fill as it splits a line.
Fill above and below zero
set terminal svg size 560,320; set output 'cb_fill_zero.svg'
# filledcurves above or below without a base fills against y = 0, as gnuplot
set samples 200; set xrange [0:4*pi]; set key bottom left
set style fill transparent solid 0.4 noborder
plot sin(x) * exp(-x/8) with filledcurves above lc "#0072b2" title "above", \
sin(x) * exp(-x/8) with filledcurves below lc "#d55e00" title "below", \
sin(x) * exp(-x/8) with lines lc "black" notitleabove and below without y=V fill against y = 0, as gnuplot; next to an axis word (above x1) they are ignored. See Boxes and filled curves.
Rectangles
set terminal svg size 560,320; set output 'cb_boxxyerror.svg'
set style fill transparent solid 0.25
plot 'partition.dat' u 1:2:3:4:5:6 w boxxyerror t 'blocks', '' u 1:2 w p pt 7 t 'centres'boxxyerror draws a rectangle per row, from x:y:xdelta:ydelta or x:y:xlow:xhigh:ylow:yhigh: here the blocks of a domain decomposition.
A bubble chart
set terminal svg size 560,320; set output 'cb_circles.svg'
set style fill solid 0.4
set xlabel 'cells [M]'; set ylabel 'speedup'; set xrange [0:20]; set yrange [0:11]
plot 'scaling.dat' u 2:3:4 w circles t 'memory [GB] as radius'The third column is the radius, in x units. See Circles, pies and donuts.
A vector field with labelled probes
set terminal svg size 560,400; set output 'cb_vectors.svg'
set size square; set xrange [-3.5:3.5]; set yrange [-2.8:2.8]; set key below
plot 'flow.dat' every 2 u 1:2:(2*$3):(2*$4) w vectors filled head t 'velocity', \
'probes_xy.dat' u 1:2:3 w labels left offset 1,0 point pt 7 tc 'red' notitlevectors draws an arrow from x:y by xdelta:ydelta (head, heads, nohead, backhead, filled); labels writes the text of a column at each point, here with its point and an offset. See Vectors, ellipses, polygons, labels and sectors. In the HTML page the heads and the labels keep their size while the zoom moves them with the data.
Arrow styles on vectors
set terminal svg size 560,360; set output 'cb_vector_heads.svg'
# vectors with arrow styles: as N gives the heads, size and color of set style arrow N; size screen L,A per item
set style arrow 1 head filled size screen 0.025,25 lc rgb '#0072b2' lw 2
set style arrow 2 heads empty size screen 0.02,40 lc rgb '#d55e00'
set xrange [0:10]; set yrange [0:4]
plot sample [i=1:9:1] '+' using (i):(3):(0.6):(0.5) with vectors as 1 title 'as 1', \
[i=1:9:1] '+' using (i):(1.5):(0.6):(-0.5) with vectors as 2 title 'as 2', \
[i=1:9:2] '+' using (i):(0.5):(0.8):(0) with vectors size 0.4,15 filled lc rgb '#009e73' title 'size 0.4,15'with vectors as N takes the heads, the fill, the head size and the color of set style arrow N; size L,A (x axis values, or screen, graph, character) and filled set them on the item. See Vectors, ellipses, polygons, labels and sectors.
A style per arrow
set terminal svg size 560,360; set output 'cb_arrowstyle_var.svg'
# a style per arrow: the fifth column names `set style arrow N` (heads, fill, width, color)
set style arrow 1 head filled size screen 0.02,20 lc rgb "#0072b2" lw 2
set style arrow 2 heads nofilled lc rgb "#d55e00" lw 1
set style arrow 3 nohead lc rgb "#009e73" lw 3 dt 2
unset key; set xrange [0:13]; set yrange [-1.5:1.5]
plot '+' using ($0):(sin($0/2)):(0.8):(0.5*cos($0/2)):(int($0)%3 + 1) with vectors arrowstyle variablearrowstyle variable (as variable) takes the number of an arrow style from the column after the vector's: each arrow its heads, fill, width and color. See Vectors, ellipses, polygons, labels and sectors.
A Gantt chart
set terminal svg size 560,320; set output 'cb_gantt.svg'
# a Gantt chart: vectors from start to end, the task names as y tick labels, the title placed in graph coordinates
$TASKS << EOD
mesh 0 3
solver 2 9
post 8 11
report 10 12
EOD
set xrange [0:13]; set yrange [4.5:0.5]; set xlabel 'week'; set grid x
set key noautotitle
plot $TASKS using 2 : ($0 + 1) : ($3 - $2) : (0) : ytic(1) with vectors nohead lw 12 lc "steelblue", \
keyentry title 'schedule' at graph 0.98, graph 0.92Each task is a vector from its start to its end, without a head, thick; ytic(1) names its row. The blanks around the colons of using are read as gnuplot does, and title ... at graph X, Y places a key entry in the plot area. See Vectors.
Arrows by length and angle
set terminal svg size 560,320; set output 'cb_arrows.svg'
set xrange [0:6]; set yrange [0:4.5]; set key below
plot 'stations.dat' u 1:2:3:4 w arrows lw 2 t 'wind (length: speed, angle: direction)', \
'' u 1:2:5 w labels right offset -1,0 notitlearrows takes x:y:length:angle, the length in x units and the same on the page at any angle (in degrees).
Uncertainty ellipses
set terminal svg size 560,320; set output 'cb_ellipses.svg'
set style fill transparent solid 0.2; set key top left
plot 'ellipses.dat' u 1:2:3:4:5 w ellipses t '1-sigma ellipses', '' u 1:2 w lp pt 7 t 'calibration'ellipses takes x:y:major:minor:angle, the diameters in x and y units, rotated on the page as gnuplot does.
Polygons from blocks
set terminal svg size 560,320; set output 'cb_polygons.svg'
set style fill solid 0.3 border; set size ratio 0.7
plot 'cells.dat' w polygons t 'cells'polygons closes each block of the file (blocks end at a blank line) into a polygon in the fill style: mesh cells, regions, outlines.
The area under a curve
set terminal svg size 560,320; set output 'cb_area.svg'
# the area under a curve (to the bottom of the plot, x1), and a closed polygon
$SHAPE << EOD
6 0.2
9 0.2
9.5 0.6
7.5 0.9
5.5 0.6
EOD
set style fill transparent solid 0.4; set xrange [0:10]; set yrange [0:1]; set key top left
plot 'run.dat' u ($1/20):($5*3 - 0.6) w filledcurves x1 t 'to the bottom (x1)', \
$SHAPE w filledcurves closed t 'closed'filledcurves x1 fills down to the bottom of the plot, closed fills the polygon of the points.
Fills to the borders
set terminal svg size 560,320; set output 'cb_fill_borders.svg'
# fills across: to the left border (y1), to the right one (y2), to the vertical line x = 5
$HIGH << EOD
2 7.2
3 7.8
4 7.0
5 8.1
EOD
$MID << EOD
5 4.0
6 4.6
7 4.2
8 5.0
EOD
$LOW << EOD
1 1.0
3 2.2
5 1.6
7 2.6
9 1.8
EOD
set xrange [0:10]; set yrange [0:9]; set key top center horizontal
plot $HIGH w filledcurves y1 fs solid 0.6 t 'y1', $MID w filledcurves y2 fs solid 0.6 t 'y2', \
$LOW w filledcurves x=5 fs pattern 4 t 'x=5', $LOW w lp pt 7 lc 'black' notitley1 fills across to the left border, y2 to the right one, x=5 to the vertical line x = 5, as gnuplot 6.0. See Boxes and filled curves.
Functions filled
set terminal svg size 560,320; set output 'cb_function_fills.svg'
# functions filled as data: a band from a level, a closed curve, boxes of the samples over their own range
set samples 41
set xrange [0:10]; set yrange [0:8]
set key top right
set style fill transparent solid 0.35
plot 5 + sin(x) with filledcurves y=5 title 'filledcurves y=5', \
2 + cos(x)*exp(-x/5) with filledcurves closed title 'filledcurves closed', \
[0:4] 0.6*x with boxes fs solid 0.6 title 'boxes, [0:4]'A function takes with filledcurves (to a level y=V, closed, x1, ...) and with boxes as data does, its samples filled; a range before an item, [0:4] 0.6*x, samples that function alone over it. See Filled curves and Plot items.
A color per shape
set terminal svg size 560,320; set output 'cb_lc_shapes.svg'
# a color per shape: boxes and circles take lc variable, the last using column a linetype
$D << EOD
1 3 0.30 1
2 5 0.40 2
3 2 0.25 3
4 6 0.50 4
5 4 0.35 5
EOD
set style fill solid 0.5
set xrange [0:6]; set yrange [0:8]
plot $D using 1:2:4 with boxes lc variable notitle, $D using 1:($2 + 1):3:4 with circles lc variable notitlelc variable colors each box, circle or ellipse by the last using column, a linetype number (lc rgb variable: a 24-bit color). See Colors.
Labels, arrows and objects
set terminal svg size 640,400; set output 'cb_annotations.svg'
# labels, arrows and objects in data, graph and page coordinates
set title 'labels, arrows, objects'; set grid; set xrange [0:10]
set object 1 rect from 4, graph 0 to 6, graph 1 fc rgb '#56b4e9' fs solid 0.25 noborder behind
set object 2 rect from 8,0.6 to 9.8,0.95
set object 3 circle at 2,-0.5 size 0.6 fc rgb '#e69f00' fs solid 0.5 border
set object 4 ellipse at 7,-0.6 size 1.6,0.5 angle 30
set object 5 polygon from 0.5,0.6 to 1.5,0.6 to 1,0.95 to 0.5,0.6 fc lt 2 fs solid 0.6 front
set label 1 'peak' at pi/2, 1 point pt 7 offset 1,0
set label 2 'transient' at graph 0.5, 0.5 center
set label 3 'rotated' at 9.2,-0.9 rotate by 60 tc rgb 'red'
set label 4 'screen 0.98, 0.03' at screen 0.98, 0.03 right front
set arrow 1 from 3,-0.2 to 4.6,-0.9
set arrow 2 from 3,0.2 to 4.6,0.8 heads filled lc rgb '#9400d3' lw 2
set arrow 3 from 8.9,0.2 rto -1,0.3 backhead empty size 0.3,25
set arrow 4 from graph 0.05,0.1 to graph 0.25,0.1 nohead dt 2 front
plot sin(x) lw 2 t 'sin(x)'Positions mix data (first), plot area (graph) and page (screen) coordinates; the band in graph y covers the whole height behind the grid, the polygon is in front of the curve. In the HTML page the objects zoom with the data. See Labels, arrows and objects.
Images from PNG files
set terminal svg size 560,320; set output 'cb_pixmap.svg'
# PNG images on the page: a badge in the corner, one per marked point
set pixmap 1 'badge.png' at screen 0.97, 0.94 width screen 0.06 center front
set pixmap 2 'badge.png' at 2, sin(2) center width char 2
set pixmap 3 'badge.png' at 5, sin(5) center width char 2
set key off; set xrange [0:2*pi]
plot sin(x) lw 2set pixmap N 'file.png' puts a PNG image on the page, as gnuplot 6.0: at its lower left corner (its centre with center), in any coordinates; width (or height) sets one side, the other by the image's aspect; size W,H both, none its own pixels. The SVG holds the file itself. See Labels, arrows and objects.
Fonts per text
set terminal svg size 560,320; set output 'cb_fonts.svg'
# a font per text: sizes, weights, styles and families, as gnuplot's svg terminal
set title "Damped oscillation" font ",18"
set xlabel "time [s]" font ":Italic"
set ylabel "amplitude" font ":Bold"
set xtics font ",9"; set ytics font ",9"
set key font "serif:Italic,13"
set label 1 "first peak" at 1.6, 0.76 font "serif:Bold,13"
set samples 400; set xrange [0:12]
plot exp(-x/4)*sin(x) lw 2 title "e^{-t/4} sin t", exp(-x/4) dt 2 title "envelope"Each text takes gnuplot's font "family:Bold:Italic,size": the title larger, the axis labels italic and bold, the tick labels smaller, the key and the label in a serif family. As gnuplot, only the title (and the x2 label, the key) take room by their size. See Fonts.
Boxed labels
set terminal svg size 560,320; set output 'cb_boxed_labels.svg'
# boxed labels: the text on the background, over the line (gnuplot's svg textbox)
set style textbox opaque
$D << EOD
1 3.1
2 4.7
3 6.2
4 5.4
5 6.8
6 4.9
EOD
set xrange [0.5:6.5]; set yrange [2:8]
plot $D using 1:2 with lines lw 3 title 'series', '' using 1:2:2 with labels boxed notitlewith labels boxed writes each text on the background, over the line, when the text box style is opaque or has a border, as gnuplot's svg terminal. See Labels, arrows and objects.
Hypertext on points
set terminal svg size 560,320; set output 'cb_hypertext.svg'
# labels hypertext: the texts shown on mouse-over of their points; ps variable: each point's size from a column
$CITIES << EOD
Paris 2.35 48.86 2.1
Lyon 4.84 45.76 0.5
Marseille 5.37 43.30 0.9
Toulouse 1.44 43.60 0.5
Lille 3.06 50.63 0.2
Nantes -1.55 47.22 0.3
EOD
unset key
plot $CITIES using 2:3:(sprintf("%s\npop. %.1f M", strcol(1), $4)):(1 + 2*sqrt($4)) \
with labels hypertext point pt 7 ps variable lc rgb "#e0a020", \
'' using 2:3:(1 + 2*sqrt($4)) with points pt 6 ps variable lc "black"with labels hypertext shows each text only on mouse-over of its point (hover the dots), as gnuplot's svg; ps variable sizes each point from a column. See Labels, arrows and objects.
Labels turned and colored by columns
set terminal svg size 560,360; set output 'cb_label_rotate.svg'
# labels turned by a column (rotate variable) and colored by another (tc variable)
set angles degrees; unset key
set xrange [0:13]; set yrange [0:13]
$Clock << EOD
1 one -30
2 two -60
3 three -90
4 four -120
5 five -150
6 six -180
7 seven -210
8 eight -240
9 nine -270
10 ten -300
11 eleven -330
12 twelve -360
EOD
plot $Clock using 1:1:2:3:0 with labels rotate variable tc variablewith labels rotate variable turns each label by the fourth column, tc variable colors it by the last one. See Vectors, ellipses, polygons, labels and sectors.
Labels with tic labels
set terminal svg size 560,320; set output 'cb_labels_tics.svg'
# labels with their own tic labels: the text at each point, the x tics named by a column, times on y
$EVENTS << EOD
1390852607.100 start
1390852607.400 mesh
1390852608.400 solve
1390852610.001 write
EOD
set ydata time; set timefmt "%s"; set format y "%H:%M:%.3S"
set offset 0.5, 1.5, 0.2, 0.2; unset key
plot $EVENTS using 0:1:(strftime("%.3S s", column(1))):xticlabels(2) with labels point pt 7 left offset 1,0.5with labels takes xticlabels() (and yticlabels()) besides its text column: the text at the point, the names under the axis. %.3S rounds the milliseconds, as gnuplot. See Time data.
Arrow styles and dashed objects
set terminal svg size 560,360; set output 'cb_arrow_styles.svg'
# arrow styles, the rectangle style, dashed borders, character coordinates
set style arrow 1 head filled size screen 0.025,15 lc rgb '#b3163f' lw 2
set style arrow 2 nohead lc rgb '#0072b2' dt 2
set arrow from 1,1 to 4,4 as 1
set arrow from 1,4 to 4,1 as 2
set arrow from 6,8.5 to 8.2,6.6 as 1 lc rgb '#009e73'
set style rectangle fc rgb '#fff3b0' fs solid border lc rgb '#e69f00' lw 2
set object 1 rect from 5,1 to 7,3
set object 2 rect from 1.5,6 to 3.5,8 dt 2 fc rgb '#dfe9ff'
set object 3 circle at 8,8 size 1 dt 3 lw 1.5
set label 'at character 9, 5' at character 9, 5
set xrange [0:10]; set yrange [0:10]; set key off
plot 5 dt 3 lc 'gray' notitleset style arrow N names a look, as N applies it (an option after it changes that one only); set style rectangle gives the rectangles set next their fill and border; dt N dashes an object's border; a label at character X, Y stands X cells from the left and Y up from the bottom of the page.
Heatmaps and images
A heatmap
set terminal svg size 560,400; set output 'cb_image.svg'
set cblabel 'phi'
plot 'field.dat' u 1:2:3 w image t 'phi(x,y)'x:y:z points on a regular grid, colored by the default palette; the color box at the right.
A heat map of sparse data
set terminal svg size 520,400; set output 'cb_sparse_matrix.svg'
# a distance matrix given as its upper triangle: sparse matrix bins the points into a 4x4 grid, the rest empty
$DIST << EOD
1 1 0
1 2 20
1 3 30
1 4 40
2 2 0
2 3 50
2 4 60
3 3 0
3 4 20
4 4 0
EOD
set xrange [0.5:4.5]; set yrange [4.5:0.5]
set xtics 1; set ytics 1
set palette cubehelix negative
plot $DIST sparse matrix=(4,4) origin=(1,1) with image notitlesparse matrix=(4,4) origin=(1,1) bins the given points into a 4 by 4 grid, each in its nearest cell, the cells without a point left empty: here a distance matrix given as its upper triangle. See plot items.
A table with named rows and columns
set terminal svg size 560,360; set output 'cb_matrix_headers.svg'
# a CSV table as a heat map: its first row and column name the columns and rows (matrix columnheaders rowheaders)
$sales << EOD
,Q1,Q2,Q3,Q4
North,12,15,9,20
South,8,11,14,10
East,5,7,12,16
EOD
set datafile separator comma
set palette viridis
set title 'units sold'
plot $sales matrix rowheaders columnheaders using 1:2:3 with image notitlematrix rowheaders columnheaders reads a CSV table as gnuplot does: its first row names the columns, the first cell of each row names it, and the names become the tick labels. See plot items.
A matrix file
set terminal svg size 560,400; set output 'cb_matrix.svg'
set palette viridis maxcolors 10
set xlabel 'sweep'; set ylabel 'block'; set cblabel 'residual'
plot 'blocks.dat' matrix w image notitlematrix reads the values as they lie in the file: columns along x, rows along y. maxcolors 10 quantizes the palette. See Images and palettes.
A matrix with its coordinates
set terminal svg size 560,360; set output 'cb_nonuniform.svg'
# a nonuniform matrix: x in the first row, y in the first column; index "name" picks the dataset of that comment
$M << EOM
# coarse
0 0 1
0 1 2
1 3 4
# fine
0 0 0.5 1 1.5
0 0 1 2 3
0.5 1 2 3 4
1 2 3 4 5
EOM
set palette viridis
plot $M nonuniform matrix index "fine" with image title 'index "fine"'nonuniform matrix reads the x of the columns in the first row and the y of the rows in the first column; index "fine" picks the dataset after the comment line # fine. See Images and palettes.
Statistics of a matrix
set terminal svg size 560,320; set output 'cb_stats_matrix.svg'
# stats of a matrix: its size and extremes, also of the part `every` keeps; every on a matrix image
$M << EOM
3 3 3 3 3 3 3
3 4 4 4 4 4 3
3 4 5 5 5 4 3
3 4 5 6 5 4 3
3 4 5 5 5 4 3
3 4 4 4 4 4 3
3 3 3 3 3 3 3
EOM
stats $M every ::2::4 matrix nooutput
set title sprintf("columns 2 to 4: %d x %d values, mean %.2f", STATS_size_x, STATS_size_y, STATS_mean)
set xrange [-0.5:6.5]; set yrange [-0.5:6.5]; set cbrange [3:6]; unset key
plot $M every ::2::4 matrix with imagestats ... matrix gives the statistics of the values with the size of the matrix (STATS_size_x, _y) and the places of its extremes; every keeps columns (points) and rows (blocks) of a matrix, for stats and for the image. See Stats.
Palettes
set terminal svg size 760,560; set output 'cb_palettes.svg'
set multiplot layout 2,2
unset colorbox
set title 'gray'; set palette gray
plot 'field.dat' u 1:2:3 w image notitle
set title 'rgbformulae 33,13,10'; set palette rgbformulae 33,13,10
plot 'field.dat' u 1:2:3 w image notitle
set title 'defined'; set palette defined (0 'blue', 1 'white', 2 'red')
plot 'field.dat' u 1:2:3 w image notitle
set title 'cubehelix'; set palette cubehelix
plot 'field.dat' u 1:2:3 w image notitle
unset multiplotset palette gray, rgbformulae R,G,B (any of gnuplot's 37), defined (v color, ...), cubehelix [start S] [cycles C] [saturation S], viridis, with negative and maxcolors N. See Images and palettes.
A palette in hue, saturation and value
set terminal svg size 560,360; set output 'cb_palette_hsv.svg'
# a color wheel: the palette in hue, saturation, value (model HSV), the hue from the angle
set print $WHEEL
do for [j = 0:60] {
do for [i = 0:60] {
x = -1 + i/30.0; y = -1 + j/30.0
print x, y, (x*x + y*y <= 1 ? atan2(y, x)/(2*pi) + 0.5 : NaN)
}
print ""
}
set print
set palette model HSV defined (0 0 1 1, 1 1 1 1)
set size square
set cbrange [0:1]; set cblabel 'hue'
plot $WHEEL using 1:2:3 with image notitleset palette model HSV reads the palette's three components as hue (0 to 1), saturation and value; defined (v h s v, ...) takes them as numbers. See Palettes.
A palette of functions
set terminal svg size 560,320; set output 'cb_palette_functions.svg'
# a palette of functions of gray: in HSV, the hue running from red to blue
set palette model HSV functions gray * 0.66, 0.8, 0.95
set samples 120
set table $S; plot [0:10] sin(x) * exp(-x / 8); unset table
plot $S using 1:2:2 with points pt 7 ps 1.2 lc palette z notitleset palette functions R, G, B gives the three components as expressions of gray, here hue, saturation and value (model HSV). See Images and palettes.
A log color axis
set terminal svg size 560,400; set output 'cb_logcb.svg'
set logscale cb; set cblabel 'residual'
set cbtics 10
plot 'field.dat' u 1:2:(10**(3*$3)) w image notitleset logscale cb maps the values on a log scale, for residuals spanning decades; set cbtics, set format cb and unset cbtics set the labels of the color box as those of the x and y axes. See Images and palettes.
Color box placement
set terminal svg size 760,320; set output 'cb_colorbox.svg'
set multiplot layout 1,2
set palette viridis; set cblabel 'phi'
set title 'set colorbox horizontal'; set colorbox horizontal
plot 'field.dat' u 1:2:3 w image notitle
set title 'set colorbox user ... invert'
set colorbox vertical user origin 0.86,0.3 size 0.02,0.45 invert
plot 'field.dat' u 1:2:3 w image notitle
unset multiplotset colorbox horizontal lays the box below the plot; user origin X,Y size W,H puts it anywhere on the page (fractions from the bottom left), invert turns a vertical box upside down, noborder drops its frame. See Images and palettes.
A palette from a file
set terminal svg size 560,400; set output 'cb_palette_file.svg'
set palette file 'terrain.dat'
set cbrange [-1:1]; set cblabel 'height'
plot 'field.dat' u 1:2:3 w image notitleset palette file 'terrain.dat' reads a gradient as gnuplot: gray r g b rows (here sea below 0.5, land above), or r g b rows evenly spaced; using, index and every work as in plot. See Images and palettes.
Named palettes
set terminal svg size 760,560; set output 'cb_colormaps.svg'
set multiplot layout 2,2
set title 'batlow: sequential'; set palette batlow
plot 'field.dat' u 1:2:3 w image notitle
set title 'vik: diverging, about 0'; set palette vik; set cbrange [-1:1]
plot 'field.dat' u 1:2:3 w image notitle
set title 'oleron: below and above 0'; set palette oleron; set cbrange [-1:1]
plot 'field.dat' u 1:2:3 w image notitle
set title 'romaO: cyclic, an angle'; set palette romaO; set cbrange [-180:180]
plot 'angle.dat' u 1:2:3 w image notitle
unset multiplotA foresight extension: set palette NAME, one of Crameri's Scientific colour maps, matplotlib's magma, inferno, plasma, viridis, cividis, or Moreland's black_body, in any case. Pick the type for the data: sequential for a magnitude, diverging about a meaningful centre (a symmetric cbrange), multi-sequential for two regimes either side of a value, cyclic for an angle (cbrange [-180:180], the ends meet). See Named palettes for every name.
Images from binary files
set terminal svg size 560,320; set output 'cb_binary.svg'
# binary arrays: raw RGB bytes (32 x 16 pixels, one %uchar per channel) as images, placed, scaled and flipped
set key outside
plot 'gradient.rgb' binary array=(32,16) format='%uchar' with rgbimage title 'raw', \
'gradient.rgb' binary array=(32,16) format='%uchar' flipy dx=0.5 origin=(36,0) with rgbimage title 'flipy dx=0.5'binary array=(W,H) format='%uchar' reads raw bytes, a pixel after the other, as gnuplot: flipy puts the first scan line on top, dx, dy and origin place and scale the pixels. See Images and palettes.
Rotated images
set terminal svg size 560,360; set output 'cb_binary_rotate.svg'
# a binary image placed by its centre and turned: right angles stay pixels, other angles draw each pixel a polygon
set size ratio -1
set xrange [-24:84]; set yrange [-24:44]
set key outside
plot 'gradient.rgb' binary array=(32,16) format='%uchar' center=(0,10) with rgbimage title 'center=(0,10)', \
'gradient.rgb' binary array=(32,16) format='%uchar' center=(30,10) rotation=90d with rgbimage title 'rotation=90d', \
'gradient.rgb' binary array=(32,16) format='%uchar' center=(62,10) rotation=30d with rgbimage title 'rotation=30d'center=(X,Y) places a binary image by its centre and rotation=A turns it about that centre (90d, 0.5pi or radians), as gnuplot: a right angle keeps the pixels a grid, any other one draws each pixel as a small polygon. See Images and palettes.
Colors as numbers
set terminal svg size 560,360; set output 'cb_rgb_numbers.svg'
# lc rgb with numbers (0xRRGGBB, 0xAARRGGBB with a transparency): a key wrapped into columns when tall
unset tics; unset border; set key center center; set style fill solid
plot 0 lt nodraw notitle, for [i = 0:35] keyentry with boxes lc rgb (int(255*i/35.)*65536 + int(255*(35-i)/35.)*256 + 128) \
title sprintf("0x%06x", int(255*i/35.)*65536 + int(255*(35-i)/35.)*256 + 128)lc rgb N takes a number, 0xRRGGBB (0xAARRGGBB with a transparency): here an expression per entry; a key taller than the page wraps into columns, as gnuplot. See Key.
Named colormaps
set terminal svg size 560,360; set output 'cb_named_colormaps.svg'
# named colormaps: each saved from a palette, then chosen per item by lc palette NAME
set palette defined (0 "gray90", 1 "dark-blue"); set colormap new blues
set palette defined (0 "dark-red", 1 "yellow"); set colormap new flame
set palette cubehelix; set colormap new ch
unset colorbox; set key off; set xrange [0:21]; set yrange [-1.5:4]
set samples 21
plot '+' using 1:(sin($1/3)):1 with points pt 7 ps 1.5 lc palette blues, \
'+' using 1:(1.2 + sin($1/3)):1 with points pt 7 ps 1.5 lc palette flame, \
'+' using 1:(2.4 + sin($1/3)):1 with points pt 7 ps 1.5 lc palette chset colormap new NAME saves the current palette, lc palette NAME colors an item's z column by it (over its own range with set colormap NAME range [a:b]). See Colors per point and from the palette.
An RGB image
set terminal svg size 560,400; set output 'cb_rgbimage.svg'
set size ratio 0.667
plot 'wheel.dat' u 1:2:3:4:5 w rgbimage t 'rgbimage'rgbimage (x:y:r:g:b) and rgbalpha (x:y:r:g:b:a) color each pixel directly, components 0 to 255 (set rgbmax 1 for fractions), without palette nor color box.
3D plots
A surface in 3D
set terminal svg size 560,400; set output 'cb_view3d_surface.svg'
# a function of x and y as a mesh of iso-curves, in gnuplot's default 3D view (set view 60, 30)
set title 'sin(x) cos(y)'
set xlabel 'x'; set ylabel 'y'; set zlabel 'z'
set isosamples 25, 25
set xrange [-3:3]; set yrange [-3:3]
splot sin(x)*cos(y) title 'surface'splot of a function of x and y draws it as a mesh of iso-curves (set isosamples) in gnuplot's default view, set view 60, 30: the box, its base plane below the z range (set xyplane relative 0.5), the x and y ticks along the front of the base, the z ticks at its left corner, the key at the top right, as gnuplot 6.0 places them. See 3D views.
One surface, two views
set terminal svg size 760,400; set output 'cb_view3d_views.svg'
# one surface seen from two sides: the view rotated, the z axis stretched, the base plane at z = 0, the whole box
set multiplot layout 1,2 title 'one surface, two views'
set isosamples 20, 20
set xrange [-3:3]; set yrange [-3:3]
unset key
set title 'set view 60, 30'
splot exp(-(x**2 + y**2)/4)*cos(x)
set view 75, 210, 1, 1.2
set xyplane at 0
set border 4095
set title 'set view 75, 210, 1, 1.2'
splot exp(-(x**2 + y**2)/4)*cos(x)
unset multiplotset view ROT_X, ROT_Z, SCALE, SCALE_Z turns the box (rot_x about the horizontal, then rot_z about the vertical) and scales it, the z axis apart; set xyplane at 0 puts the base plane at z = 0, set border 4095 draws the whole box. See 3D views.
A surface and its side projections
set terminal svg size 900,340; set output 'cb_view3d_projection.svg'
# a surface and its two side projections: the xz and yz planes seen edge-on, as gnuplot's set view projection
set multiplot layout 1,3 title 'a surface and its side projections'
set isosamples 24, 24
set xrange [-3:3]; set yrange [-3:3]
unset key
set xlabel 'x'; set ylabel 'y'; set zlabel 'z'; set ztics 0.5
f(x, y) = exp(-(x**2 + y**2)/4)*cos(x) + 0.1*y
set title 'set view 60, 30'
splot f(x, y)
set title 'set view projection xz'
set view projection xz
splot f(x, y)
set title 'set view projection yz'
set view projection yz
splot f(x, y)
unset multiplotset view projection xz and set view projection yz show the surface on the xz and yz planes seen edge-on, as gnuplot 6.0 draws them: x (or y) vertical and z horizontal, the plane's border, the ticks on its four sides, the base plane at the bottom of the z range; set view projection xy is the map view, and set view 60, 30 turns the box again. See 3D views.
Arrows and labels in 3D
set terminal svg size 560,400; set output 'cb_view3d_arrows.svg'
# a helix with its axes drawn as arrows, their names at the tips: annotations at x,y,z positions in a 3D view
set view equal xy
set view 60, 30, 1, 1.75
set xyplane at 0
unset border; unset key; unset xtics; unset ytics
set ztics axis
set arrow 1 from 0,0,0 to 1,0,0 head filled lw 1.5
set label 1 'x' at 1.2,0,0 center
set arrow 2 from 0,0,0 to 0,1,0 head filled lw 1.5
set label 2 'y' at 0,1.2,0 center
set arrow 3 from 0,0,0 to 0,0,21 head filled lw 1.5
set label 3 'z' at 0,0,23 center
splot sample [t=0:20] '+' using (cos($1)):(sin($1)):($1) with lines lw 2set arrow and set label take a third coordinate in a 3D view: x, y, z axis values projected as the data (graph ones fractions of the three axes, screen ones as they are), here the axes drawn as arrows from the origin; set ztics axis puts the z ticks on the z axis through x = y = 0. See 3D views.
Points on a sphere
set terminal svg size 560,420; set output 'cb_view3d_sphere.svg'
# longitude and latitude on a sphere: set mapping spherical reads splot's data as theta:phi[:r]
set angles degrees
set mapping spherical
set view equal xyz
set view 60, 30, 1.3
set xyplane at -1
set urange [0:360]; set vrange [-90:90]
set isosamples 25, 13
unset key
$cities << EOD
12.5 41.9 1 Rome
-74.0 40.7 1 "New York"
139.7 35.7 1 Tokyo
151.2 -33.9 1 Sydney
EOD
splot '++' using 1:2:(1) with lines lc 'gray', $cities using 1:2:3:4 with labels point pt 7 left offset 1,0set mapping spherical reads splot's data as longitude, latitude and radius (1 when there are two columns), in the set angles unit, as gnuplot: the '++' grid of longitudes and latitudes is a sphere, the cities its labelled points; set view equal xyz keeps it round. See 3D views.
Hidden lines
set terminal svg size 560,400; set output 'cb_view3d_hidden.svg'
# a parametric surface with hidden lines: opaque, its underside in the next color, the key below
set parametric
set hidden3d
set isosamples 36, 12
set urange [0:2*pi]; set vrange [-1:1]
set view 60, 30
set key below
set title 'a Moebius strip'
splot (1 + v/2*cos(u/2))*cos(u), (1 + v/2*cos(u/2))*sin(u), v/2*sin(u/2) title 'strip'set hidden3d draws the surface opaque, painted from the farthest quadrangle to the nearest; the side seen from below takes the next linetype, so the Moebius strip shows its single side in two colors where it twists. See 3D views.
Smoothed profiles in 3D
set terminal svg size 560,400; set output 'cb_view3d_smooth.svg'
# measured profiles at three depths smoothed in 3D: each scan a smoothing spline of its plane (gnuplot's 3D acsplines)
$P << EOD
0 0 1.0
0 1 1.9
0 2 1.4
0 3 2.6
0 4 2.1
0 5 2.4
1 0 0.8
1 1 1.5
1 2 1.6
1 3 2.2
1 4 2.4
1 5 2.0
2 0 0.5
2 1 1.2
2 2 1.0
2 3 1.8
2 4 1.7
2 5 1.9
EOD
set view 60, 30
set xyplane at 0
set xlabel 'depth'; set ylabel 'position'; set zlabel 'value'
set key below
splot $P using 1:2:3 with points pt 7 title 'measured', \
$P using 1:2:3:(2) smooth acsplines lw 2 title 'acsplines, weight 2'smooth acsplines in splot smooths each scan of the data in 3D: here each profile lies in a plane of constant depth, so it is splined as value of position, weighted by the fourth using field, as gnuplot's 3D splines. See 3D views.
A field seen from above
set terminal svg size 560,400; set output 'cb_map_points.svg'
# a field sampled at scattered points, seen from above: gnuplot's map view of a 3D plot
set view map
set title 'samples of x exp(-x^2 - y^2)'
set xlabel 'x'; set ylabel 'y'; set cblabel 'value'
set palette viridis
set xrange [-2:2]; set yrange [-2:2]
set samples 400
splot '+' using (r = 1.9*sqrt(rand(0)), t = 2*pi*rand(0), px = r*cos(t)):(py = r*sin(t)):(px*exp(-px**2 - py**2)) \
with points pt 7 ps 0.8 lc palette notitlesplot plots points with a height; set view map looks at them from above, as a 2D plot laid out as gnuplot's 3D map (its plot area, ticks and color box), lc palette coloring each point by its z. The using fields are plot's with the z third. See 3D plots.
A function as a colored map
set terminal svg size 560,400; set output 'cb_map_pm3d.svg'
# a function of x and y as a colored map: gnuplot's pm3d surface seen from above
set view map
set title 'sin(x) cos(y)'
set xlabel 'x'; set ylabel 'y'
set samples 30, 30; set isosamples 30, 30
set xrange [-pi:pi]; set yrange [-pi:pi]
set pm3d interpolate 2,2
splot sin(x)*cos(y) with pm3d notitlewith pm3d draws a surface as quadrangles colored by the palette, gnuplot's pm3d: seen from above it is a heatmap of the function's grid (set samples, set isosamples), each cell split 2 by 2 (set pm3d interpolate 2,2). See 3D plots.
A map in RGB colors
set terminal svg size 560,400; set output 'cb_pm3d_rgb.svg'
# a map colored by RGB values computed per point (pm3d lc rgb variable), each tile outlined
rgb(r, g, b) = int(255*r)*65536 + int(255*g)*256 + int(255*b)
set view map
set size ratio -1
set samples 16; set isosamples 16 # the '++' grid: 16 x 16 points of the u and v ranges
set urange [0:1]; set vrange [0:1]
set pm3d border lc 'white' lw 0.5
unset colorbox
set title 'red along x, blue along y'
splot '++' using 1:2:(0):(rgb($1, 0.3, $2)) with pm3d lc rgb variable notitlelc rgb variable (or fc rgb variable) colors each quadrangle of a pm3d surface by the fourth using field, a packed color 0xRRGGBB (0xAARRGGBB with a transparency): a quadrangle takes the mean of its corners channel by channel, as gnuplot. set pm3d border outlines the quadrangles, here in white. See 3D plots.
Colors from the palette
set terminal svg size 560,400; set output 'cb_palette_function.svg'
# points colored by palette(z) with a transparency in the top byte (lc rgb variable)
set cbrange [-1:1]
set palette rgbformulae 33,13,10
set samples 60
set key off
set title 'palette(z) colors, half transparent'
alpha = 0x80000000
plot sample [t=0:2*pi] '+' using (cos(t)):(sin(2*t)):(alpha + palette(sin(3*t))) \
with points pt 7 ps 3 lc rgb variablepalette(z) is the 24-bit color of z in the current palette over cbrange, as gnuplot 6.0: added to a transparency in the top byte (0x80000000, half) it colors the points through lc rgb variable. See Images and palettes.
A colored surface in 3D
set terminal svg size 560,400; set output 'cb_view3d_pm3d.svg'
# a colored surface in a 3D view, its map on the base plane (set pm3d at bs)
set samples 40; set isosamples 40
set xrange [-3:3]; set yrange [-3:3]
set view 55, 35
set pm3d at bs
set palette rgbformulae 33,13,10
set key off
set title 'pm3d at the base and at the surface'
splot exp(-(x*x + y*y)/3)*cos(x*y) with pm3dwith pm3d in a 3D view draws the surface as colored quadrangles, gnuplot's pm3d_plot: set pm3d at bs puts them on the base plane, a map of the heights, and at the surface, in that order; the color box stands beside the plot. See 3D views.
A lit surface
set terminal svg size 560,400; set output 'cb_view3d_lighting.svg'
# a lit surface: the primary light, its highlights and a red spotlight (set pm3d lighting)
set samples 50; set isosamples 50
set xrange [-3:3]; set yrange [-3:3]
set view 50, 30
set pm3d lighting primary 0.6 specular 0.4 spec2 0.3
set pm3d depthorder
unset colorbox
set key off
set title 'pm3d lighting primary 0.6 specular 0.4 spec2 0.3'
splot cos(sqrt(x*x + y*y)*2)*exp(-(x*x + y*y)/8) with pm3d fc 'light-blue'set pm3d lighting shades the quadrangles of a surface as gnuplot does: primary the share of the light fixed with respect to the viewer, specular its highlights, spec2 a red spotlight on the faces turned away (set pm3d spotlight moves and colors it). A fill color (fc) is lit as the palette colors are. See 3D views.
A surface filled between its levels
set terminal svg size 560,400; set output 'cb_view3d_contourfill.svg'
# a surface filled between its contour levels: the slices of z at the z ticks (set contourfill ztics)
set samples 41; set isosamples 41
set xrange [-3:3]; set yrange [-3:3]
set view 55, 30
set palette viridis
set pm3d depthorder border lc 'black' lw 0.5
set contourfill ztics
set key off
set title 'splot with contourfill, set contourfill ztics'
splot exp(-(x*x + y*y)/3)*cos(x*y) with contourfillwith contourfill draws the pm3d surface in slices of z, each in the palette color of its middle: set contourfill ztics slices it at the z ticks (cbtics at the color box's, auto N in N equal slices). In a map view (set view map) it is a filled contour map. See 3D views.
Error bands in 3D
set terminal svg size 560,400; set output 'cb_view3d_zerrorfill.svg'
# curves in 3D with their error bands (splot with zerrorfill), the far ones first
$D << EOD
0 0.0 0.3
1 0.8 0.3
2 1.2 0.4
3 1.0 0.3
4 1.6 0.5
5 2.1 0.4
6 1.9 0.5
EOD
set view 60, 25
set xyplane 0
set yrange [0.5:3.5]
set grid x y z vertical
set key top left
set title 'splot with zerrorfill'
splot for [k=3:1:-1] $D using 1:(k):($2*k):($3*k/2) with zerrorfill lt black fc lt k title sprintf('run %d', k)with zerrorfill draws each curve with a band from its low to its high z ends, in its fill color, and the line through z in its line color; the items are plotted back to front. See 3D views.
Grid walls
set terminal svg size 560,400; set output 'cb_view3d_walls.svg'
# a surface boxed by the grid walls (set wall), drawn behind or in front as they face
set wall z0 fs transparent solid 0.5 border -1 fc 'slategray'
set wall x0 fs transparent solid 0.5 border -1 fc 'forest-green'
set wall y0 fs transparent solid 0.5 border -1 fc 'bisque'
set xrange [0:1]; set yrange [0:1]
set xyplane at 0
set isosamples 25,25
set palette cubehelix
unset colorbox; unset key
set view 65, 145
set title 'set wall x0, y0, z0'
splot .1 + y*sin(20*(x-0.5))/(20*(x-0.5)) with pm3dset wall fills the planes of the graph box (x0, y0, z0, x1, y1) half transparent and borders them in black; each is drawn behind the plot or over it as it faces. See 3D views.
Bars in 3D
set terminal svg size 560,400; set output 'cb_view3d_boxes.svg'
# bars in 3D: splot with boxes, a depth (set boxdepth), lit and sorted by depth
$D << EOD
1 3 2 4
2 5 3 6
3 4 6 5
4 6 4 3
EOD
set boxwidth 0.4 absolute
set boxdepth 0.4
set style fill solid border lc 'black'
set pm3d depthorder base border lc 'black'
set pm3d lighting primary 0.5 specular 0.2
set xyplane at 0
set xrange [0:5]; set yrange [0:4]
set xtics 1; set ytics 1,1,3
set grid z vertical
set view 59, 24
unset key
set title 'splot with boxes, set boxdepth 0.4'
splot for [k=1:3] $D using 1:(k):k+1:(k == 1 ? 0x0072b2 : k == 2 ? 0xe69f00 : 0x009e73) with boxes fc rgb variablesplot ... with boxes draws a bar at each point, set boxdepth gives it a depth along y; with set pm3d depthorder base the faces of every bar are drawn from the farthest, and set pm3d lighting shades them. See 3D views.
An isosurface of a voxel grid
set terminal svg size 560,400; set output 'cb_view3d_isosurface.svg'
# a voxel grid filled around a helix, its points and the surface enclosing them
set vgrid $helix size 25
set vxrange [-2:2]; set vyrange [-2:2]; set vzrange [0:11]
set xrange [-2:2]; set yrange [-2:2]; set zrange [0:11]
vfill sample [t=0:20] '+' using (cos($1)):(sin($1)):($1):(0.9):(10.0)
set view 60, 30, 1.6
set xyplane at 0
set style fill transparent solid 0.3
set pm3d depthorder border lc 'blue' lw 0.4
set key off
set title 'isosurface of a voxel grid (vfill, with isosurface)'
splot $helix with isosurface level 1.0 lt 3set vgrid makes a grid of N x N x N values, vfill adds a density around each data point (here 10 within 0.9 of the points of a helix), and with isosurface level L draws the surface where the values cross L, by marching cubes as gnuplot 6.0; with points above L would draw the grid points themselves. See Voxel grids.
Solids from polygons
set terminal svg size 560,400; set output 'cb_view3d_polygons.svg'
# a solid from its faces: splot with polygons, depth sorted and lit
$CUBE << EOD
0 0 0
1 0 0
1 1 0
0 1 0
0 0 1
1 0 1
1 1 1
0 1 1
0 0 0
1 0 0
1 0 1
0 0 1
0 1 0
1 1 0
1 1 1
0 1 1
0 0 0
0 1 0
0 1 1
0 0 1
1 0 0
1 1 0
1 1 1
1 0 1
EOD
set view equal xyz
set view 60, 35, 1.4
set xrange [-0.5:1.5]; set yrange [-0.5:1.5]; set zrange [-0.5:1.5]
unset border; unset tics; unset key
set pm3d depthorder border lc 'black' lw 1.5
set pm3d lighting primary 0.6 specular 0.3
set style fill transparent solid 0.8
set title 'splot with polygons, set pm3d depthorder lighting'
splot $CUBE with polygons fc 'steelblue'splot ... with polygons draws a polygon per block of the data; with set pm3d depthorder they are drawn from the farthest, and set pm3d lighting shades each face. set object N polygon ... depthorder joins the same sort. See 3D views.
Contours in a 3D view
set terminal svg size 560,400; set output 'cb_view3d_contours.svg'
# contour lines on the base plane of a 3D view, their values on them (with labels)
set contour base
set cntrparam levels incremental -0.8, 0.4, 0.8
set cntrlabel start 3 interval 30
set isosamples 30, 30
set xrange [-3:3]; set yrange [-3:3]
set view 60, 30
set key off
set title 'contours of sin(x) cos(y) and their values'
splot sin(x)*cos(y) lc 'gray50', sin(x)*cos(y) with labels boxed notitleset contour base draws the contour lines of the surface on the base plane of the 3D view, each level in its own linetype; the same function with labels writes the values on the lines, boxed, from the third point every thirty (set cntrlabel start 3 interval 30), as gnuplot. See Contours.
Labels in palette colors
set terminal svg size 560,400; set output 'cb_view3d_label_colors.svg'
# labels colored by their height on the palette (tc palette z): the color axis spans z
set xrange [-3:3]; set yrange [-3:3]; set zrange [-1:1]
set isosamples 30, 30
set view 60, 30
set palette rgbformulae 33,13,10
do for [k=-2:2] {
set label k+3 sprintf('z = %4.1f', 0.5*k) at -3, 3.4, 0.5*k right tc palette z
}
set title 'heights in palette colors'
splot exp(-(x*x + y*y)/2)*cos(2*x) lc 'gray50' notitletc palette z colors a label by its own height through the palette, tc palette cb V by a value, tc palette frac F by a fraction of the palette. With no item colored by the palette, the color axis spans the heights of the surface, as gnuplot: the labels then read as a legend of the heights. See Labels, arrows and objects.
Contour lines over a map
set terminal svg size 560,400; set output 'cb_map_contour.svg'
# contour lines over a pm3d map: the levels of a function, a linetype and a key entry each
set view map
set pm3d at b; unset surface
set contour base
set cntrparam levels incremental -0.75, 0.5, 0.75
set samples 40, 40; set isosamples 40, 40
set xrange [-3:3]; set yrange [-3:3]
set palette cubehelix
set key top left box opaque
splot sin(x)*cos(y) lw 2 title 'sin(x) cos(y)'set contour traces the levels of the surface (gnuplot's contour.c), each in a linetype of its own with a key entry for its value; set pm3d at b with unset surface draws the colored map without the surface's own lines. See Contours.
A density map of scattered points
set terminal svg size 560,400; set output 'cb_map_dgrid3d.svg'
# a density map of scattered points: set dgrid3d grids them with a Gaussian kernel (kdensity sums its weights)
set print $P
do for [i=1:400] {
r = sqrt(i*0.6180339887 - floor(i*0.6180339887))
c = (i % 3 == 0) ? 1.5 : -1
print sprintf("%g %g", c + r*cos(2.4*i), 0.6*c + 0.8*r*sin(2.4*i))
}
unset print
set view map
set dgrid3d 60,60 gauss kdensity 0.35
set palette cubehelix negative
set key top left opaque
splot $P using 1:2:(1) with pm3d title 'density', \
$P using 1:2:(0) nogrid with points pt 7 ps 0.3 lc 'black' title 'points'set dgrid3d ... gauss kdensity grids the points on a 60 by 60 grid with a Gaussian kernel, each node the sum of the points' weights: a density map, drawn with pm3d; nogrid keeps the points of the second item as they are. See Gridded and masked surfaces.
A surface masked to its data
set terminal svg size 560,400; set output 'cb_map_mask.svg'
# a surface gridded from scattered points, masked to their convex hull (with mask, the mask item option)
set print $P
do for [i=1:120] {
r = 2*sqrt(i*0.6180339887 - floor(i*0.6180339887))
print sprintf("%g %g", r*cos(2.4*i) + 0.4*sin(i), 0.7*r*sin(2.4*i))
}
unset print
set table $HULL
plot $P using 1:2 convexhull with lines
unset table
set view map
set dgrid3d 50,50 gauss 0.6
set palette viridis
set key top left opaque
splot $HULL using 1:2:(0) with mask notitle, \
$P using 1:2:($1*$2) mask with pm3d title 'x y', \
$HULL using 1:2:(0) nogrid with lines lc 'black' lw 2 title 'hull'A grid from scattered points (set dgrid3d) covers their bounding box, beyond the data. Their convex hull, tabulated into $HULL, becomes a mask (with mask): the pm3d item with the mask option is drawn only inside it. See Gridded and masked surfaces.
Polar and radial charts
A polar plot
set terminal svg size 520,400 theme vfd; set output 'cb_polar.svg'
set polar; set angles degrees
set size square; unset border; set border polar; unset xtics; unset ytics
set grid polar 30; set ttics 0,30; set key outside
plot 'directivity.dat' u 1:2 w lp t 'probe', 1+cos(t) t 'cardioid'A probe's directivity against a cardioid model, theta in degrees, in gnuplot's round idiom: square plot, polar border and grid, theta labels, no x and y ticks. See Polar plots.
A reversed r axis
set terminal svg size 480,420; set output 'cb_reversed_r.svg'
# a reversed r axis: elevation 90 at the pole, the horizon on the rim, a sun path over the sky
set polar; set angles degrees; set theta top clockwise
set size square; unset border; unset xtics; unset ytics; set border polar
set rrange [90:0]; set rtics 30; set grid polar 45 lt -1 lw 0.5
set trange [60:300]; set key bottom right
plot 70 - 50*abs((t - 180)/120)**1.5 lw 2 t 'sun elevation'set rrange [90:0] puts 90 at the pole and 0 on the rim: an elevation, the horizon outside. The grid takes its line style, lt -1 lw 0.5 black and thin. See Polar plots.
A labelled radial axis and clipped curves
set terminal svg size 480,420; set output 'cb_rlabel.svg'
# set rlabel names the radial axis; titles at the beginning or end of curves, justified; polar lines clipped at the r range
set polar; set angles degrees; set theta top clockwise
set rrange [90:0]; set rtics 30 format "%.0f°"
set rlabel "altitude" offset -2
unset xtics; unset ytics; unset border; set border polar; unset key; set size square
set grid polar 45
set ttics add ("N" 0, "E" 90, "S" 180, "W" -90)
set samples 361
plot [0:360] 60*cos(t - 180) lw 2 title "summer" at end left, \
25*cos(t - 180) - 10 lw 2 title "winter" at beginning rightset rlabel names the radial axis, over its middle; a curve leaving the r range is cut at the rim, where title ... at beginning|end left|right puts its name. set ttics add places named angles alone. See Polar plots.
A surface on a polar grid
set terminal svg size 520,420; set output 'cb_polar_surface.svg'
# set polar grid: scattered theta:r:z weighted onto a polar grid and drawn with surface, the points over it
set angles degrees
set polar grid 36,8 gauss scale 15
set print $S
do for [i=1:150] {
t = 360*rand(0); r = 100*sqrt(rand(0))
print t, r, exp(-((r*cos(t) - 40)**2 + (r*sin(t) - 20)**2)/800)
}
unset print
set size square; unset xtics; unset ytics; unset border; set border polar
set rtics 25; set ttics 0,45,315; unset key
set palette viridis; set cbrange [0:1]
plot $S using 1:2:3 with surface, $S using 1:2 with points pt 7 ps 0.4 lc "white"set polar grid T,R gauss scale S and with surface weigh scattered theta:r:z points onto a polar grid of T x R cells, each drawn in the palette color of its value (qnorm, gauss, cauchy, exp or box weights, kdensity for sums), as gnuplot 6.0's polar gridded surfaces. See Polar plots.
Named angles on a polar plot
set terminal svg size 480,420; set output 'cb_polar_labels.svg'
# polar labels: theta every 45 degrees, three named angles, minor ticks on the border, the rings of the r ticks
set encoding utf8
set polar; set size square; unset border; set border polar; unset xtics; unset ytics; unset key
set grid r polar 45
set ttics 0,45 format '%g'.GPVAL_DEGREE_SIGN
set ttics add ('π/2' 90, 'π' 180, '3π/2' 270)
set mttics 3
set rrange [0:6]
plot t lw 2set ttics add names angles (here in radians, with Unicode), set mttics adds minor ticks on the polar border and set grid r polar 45 draws the rings of the r ticks and spokes every 45 degrees. See Polar plots.
A band outside a circle
set terminal svg size 480,420; set output 'cb_polar_fill.svg'
# a polar band: the area outside the circle r = 2.5 (filledcurves above r=2.5), and its curve
set polar; set size square; unset border; set border polar; unset xtics; unset ytics; unset key
set grid polar 30; set rrange [0:4]
set style fill solid 0.5
plot 3 + sin(t)*cos(5*t) with filledcurves above r=2.5, 3 + sin(t)*cos(5*t) with lines lw 2filledcurves above r=2.5 fills the band between the curve and the circle of radius 2.5 where the curve is outside it (below: inside). See Polar plots.
A log r axis
set terminal svg size 480,420; set output 'cb_polar_log.svg'
# a log r axis: decades equally spaced from the pole at r = 1, impulses from the pole, theta labels turned
set polar; set angles degrees; set size square; unset border; set border polar; unset xtics; unset ytics; unset key
set logscale r; set rrange [1:1000]; set rtics (1, 10, 100, 1000)
set grid polar 30; set ttics 0,30 rotate
set samples 37; set trange [0:360]
plot 10**(1.5 + 1.5*cos(3*t)) with impulses lw 2set logscale r spaces the decades evenly from the pole at the rrange start; impulses go from the pole and set ttics rotate turns the theta labels along their angle. See Polar plots.
Polar error bars
set terminal svg size 560,360; set output 'cb_polar_errorbars.svg'
# polar error bars: each along the radius, r - dr to r + dr
$DATA << EOD
0 1.3 0.2
30 0.9 0.1
60 0.7 0.1
90 1.0 0.3
120 1.1 0.1
150 0.5 0.1
180 1.2 0.2
EOD
set polar; set angles degrees; set grid polar 15
unset border; unset xtics; unset ytics; unset raxis
set yrange [0:1.5]; set size ratio 0.5
plot $DATA with yerrorbars lw 1.5 title "polar error bars"On a polar plot yerrorbars draw each bar along the radius, from r - dr to r + dr, its caps across it. See Polar plots.
A level in decibels
set terminal svg size 520,400; set output 'cb_polar_db.svg'
set polar; set angles degrees
set size square; unset border; set border polar; unset xtics; unset ytics
# a level in decibels: -30 dB at the pole, rings every 10 dB on the r axis
set rrange [-30:10]; set rtics 10; set raxis
set grid polar 30; set ttics 0,30; set key outside
# the model over the upper half only
set trange [0:180]
plot 'directivity.dat' u 1:(20*log10($2)) w lp pt 7 ps 0.6 t 'probe [dB]', \
20*log10(1+cos(t)) t 'cardioid, upper half'set rrange [-30:10] puts -30 dB at the pole, so a negative level is a distance from it, and the points below -30 dB are left out; set rtics 10 rings the levels on the r axis (set raxis). set trange samples the model over the upper half only, and leaves out the data beyond it too, as gnuplot.
A wind rose
set terminal svg size 520,420; set output 'cb_windrose.svg'
set polar; set angles degrees; set theta top clockwise
set size square; unset border; set border polar; unset xtics; unset ytics
set grid polar 45; set ttics 0,45; set key outside
set style fill solid 0.6 border lc 'white'
plot 'wind.dat' u ($1-20):(0):(40):2 w sectors t '< 5 m/s', \
'' u ($1-20):2:(40):3 w sectors t '>= 5 m/s'sectors draws annular sectors from azimuth:radius:angle:width, angles in the set angles unit oriented by set theta; on a polar panel they stack into a wind rose (two speed classes, one on top of the other).
A polar heat map
set terminal svg size 560,400; set output 'cb_sectors_heatmap.svg'
# a polar heat map: one annular sector per (theta, r) cell, filled from the palette by a value (fc palette)
set angles degrees
set theta top cw
f(t, r) = r * cos(t + 20*r)**2
set size ratio -1
unset border; unset tics; unset key
set xrange [-5.5:5.5]; set yrange [-5.5:5.5]
set palette viridis
set table $cells
set view map
splot sample [t=0:350:10] [r=0:4.5:0.5] '++' using (t):(r):(0)
unset table
plot $cells using 1:2:(10):(0.5):(f($1+5, $2+0.25)) with sectors fc palette fill solidEach (theta, r) cell of a polar grid is one annular sector, filled from the palette by a value: the last using column with fc palette (or lc palette z; lc rgb variable takes packed colors, hsv2rgb(h, s, v) makes them), on cartesian axes kept round by set size ratio -1. See Vectors, ellipses, polygons, labels and sectors.
A radar and a rose
set terminal svg size 480,320; set output 'cb_radar.svg'
set style fill solid 0.3
plot 'radar.dat' u 2:xtic(1) w radar t 'gpu', '' u 3 w radar t 'cpu'set terminal svg size 480,320; set output 'cb_rose.svg'
plot 'phases.dat' u 2:xtic(1) w roseA spider plot
set terminal svg size 560,400; set output 'cb_spider.svg'
set spiderplot
set style spiderplot fs transparent solid 0.25 border lw 2
set paxis 1 range [0:10]; set paxis 2 range [0:10]; set paxis 3 range [0:10]
set paxis 4 range [0:10]; set paxis 5 range [0:10]
set paxis 1 tics 2; set grid spiderplot
plot 'solvers.dat' u 2:key(1) t 'speed', '' u 3 t 'memory', '' u 4 t 'accuracy', '' u 5 t 'scaling', '' u 6 t 'robustness'set spiderplot: each item is a radial axis, each row a polygon in its color, named by key(1); set grid spiderplot draws the web at the ticks of the first axis. foresight's with radar is the transposed shorthand (an item per polygon).
Two sets of spider polygons
set terminal svg size 560,420; set output 'cb_spider_groups.svg'
# two sets of polygons on the same axes: newspiderplot starts the second; keyentry names each set
array A1 = [15, 75, 20, 43, 90, 50]
array A2 = [25, 25, 50, 50, 75, 50]
set spiderplot
set for [i=1:6] paxis i range [0:100]
set style spiderplot fs transparent solid 0.2 border lw 1 pt 6 ps 1.5
set grid spider
set key reverse
plot keyentry with spiderplot lc 3 lw 3 title "Array #1", \
for [i=1:|A1|] A1 using (A1[i]) lc 3 lw 3 title sprintf("Scale %d", i), \
newspiderplot, \
keyentry with spiderplot lc 4 lw 2 title "Array #2", \
for [j=1:|A2|] A2 using (A2[j]) lc 4 lw 2 notitlenewspiderplot starts a new set of items whose polygons share the axes of the first set; keyentry with spiderplot names a set in the key. A set takes the color and width of its first item. See Parallel axes and spider plots.
Parallel axes
set terminal svg size 560,320; set output 'cb_parallel.svg'
set paxis 1 range [0:10]; set paxis 2 range [0:10]; set paxis 3 range [0:10]
set paxis 4 range [0:10]; set paxis 5 range [0:10]; set paxis 1 tics 2
plot 'solvers.dat' u 2 w parallel lw 2 t 'speed', '' u 3 w parallel t 'memory', '' u 4 w parallel t 'accuracy', \
'' u 5 w parallel t 'scaling', '' u 6 w parallel t 'robustness'parallelaxes: each item is an axis (a column), each row a line across them; set paxis N range and set paxis N tics scale and tick each axis. See Parallel axes and spider plots.
Parallel axes with their own ranges
set terminal svg size 560,360; set output 'cb_paxis_ranges.svg'
# parallel axes: a range, tics and a reversed axis each, every line in the color of a group column
$RUNS << EOD
1.2 300 0.010 2 1
2.5 150 0.004 5 2
4.0 120 0.002 9 3
3.1 200 0.006 6 2
EOD
set style data parallelaxes
set paxis 1 range [0:5]; set paxis 2 range [350:100]; set paxis 3 range [0:0.012]
set paxis 4 range [0:10]; set for [i = 1:4] paxis i tics
plot $RUNS using 1:5 lc variable lw 2 t 'CFL', '' using 2 t 'cells', '' using 3 t 'error', '' using 4 t 'speedup'Each axis has a range ([350:100] runs downwards) and ticks of its own; lc variable on the first item reads a second field, here a group number, the color of every line. See Parallel axes and spider plots.
A pie and a donut
set terminal svg size 480,320; set output 'cb_pie.svg'
set title 'Time per step'
plot 'phases.dat' u 2:xtic(1) w pieset terminal svg size 480,320 theme vfd; set output 'cb_donut_vfd.svg'
set title 'TIME PER STEP'
plot 'phases.dat' u 2:xtic(1) w pie donut 0.6xtic(1) names the slices; the key gives their percentages.
A cluster of gauges
set terminal svg size 600,240 theme vfd; set output 'cb_gauges.svg'
plot 'run.dat' u 1 w gauge range [0:150] segments 24 format '%3.0f' t 'ITER', \
'' u 5 w gauge range [0:0.6] segments 24 format '%5.3f' t 'CD'Each gauge shows the last value of its column over a fixed range, lit in cells; with --watch the needle-less gauges follow the run. See Gauges, radars and roses.
Dashboards of the 1980s
An 1980s dashboard
set terminal svg size 640,440 theme vfd; set output 'cb_vfd.svg'
set multiplot title 'RUN MONITOR'
set origin 0,0.62; set size 0.4,0.38; set readout vertical
plot 'run.dat' u 1 w readout format '%4.0f' t 'ITER', '' u 5 w readout format '%6.4f' t 'CD'
set origin 0.4,0.62; set size 0.6,0.38; set key top left
set style fill solid segments 10
plot 'timings.dat' u 2:xtic(1) w hist t 'mesh', '' u 3 w hist t 'fluxes'
set origin 0,0; set size 1,0.62; set key top right
set logscale y; set grid
plot 'run.dat' u 1:2 w l lw 2 t 'continuity', '' u 1:3 w l lw 2 t 'momentum'
unset multiplottheme vfd turns the page into a vacuum fluorescent display; theme lcd into a backlit LCD. segments 10 cuts the bars into cells over the y range, the unlit ones drawn faintly. See Themes and segmented fills.
A liquid-crystal dashboard
set terminal svg size 640,300 theme lcd; set output 'cb_lcd.svg'
set multiplot layout 1,2
plot 'run.dat' u 1 w gauge range [0:150] segments 20 format '%3.0f' t 'ITER'
set key top right; set style fill solid segments 12
plot 'timings.dat' u 2:xtic(1) w hist t 'mesh', '' u 3 w hist t 'fluxes'
unset multiplottheme lcd: the pale green glass and dark segments of a backlit LCD, here with a segmented gauge and segmented bars. See Themes and segmented fills.
Light and dark pages
set terminal svg size 560,320; set output 'cb_identity.svg'
set title 'eight series on the grid'
set key outside; set grid; set xrange [0:6]
plot sin(x+0.4)+0.5 w lp pt 7 ps 0.6, sin(x+0.8)+1 w lp pt 7 ps 0.6, sin(x+1.2)+1.5 w lp pt 7 ps 0.6, \
sin(x+1.6)+2 w lp pt 7 ps 0.6, sin(x+2)+2.5 w lp pt 7 ps 0.6, sin(x+2.4)+3 w lp pt 7 ps 0.6, \
sin(x+2.8)+3.5 w lp pt 7 ps 0.6, sin(x+3.2)+4 w lp pt 7 ps 0.6The same script, no theme in it, drawn in the two faces of foresight's identity by the command line:
foresight -t washi -o light.svg cb_identity.gp # ink on warm paper, a crimson first series
foresight -t night -o dark.svg cb_identity.gp # light text on a near-black ground, a rose first seriesThese are the colors of this site: its figures follow the light and dark switch at the top of the page. A script that sets its own theme (set terminal svg theme vfd) keeps it. See Themes and segmented fills.
A heatmap of lit levels
set terminal svg size 560,400 theme vfd; set output 'cb_image_vfd.svg'
set palette maxcolors 8
plot 'field.dat' u 1:2:3 w image notitleAn image in the vfd theme: the palette mapped to the glow of the display.
Seven-segment readouts
set terminal svg size 560,420; set output 'cb_readout.svg'
set multiplot title 'Run monitor'
set origin 0,0.68; set size 1,0.32
set readout horizontal
plot 'run.dat' u 1 w readout format '%4.0f' t 'ITER', '' u 2 w readout format '%9.2e' t 'CONTINUITY'
set origin 0,0; set size 1,0.68
set readout vertical top right; unset key
plot 'run.dat' u 1:5 w l t 'cd', '' u 1:5 w readout format '%6.4f' t 'CD'
unset multiplotA foresight extension: the last finite value of each item in seven-segment digits, its glass fixed by the field width of format. A panel of readouts alone fills itself with digits; over a curve they lie in a window, placed as the key. See Readouts.
set terminal dumb size 72,24
set readout top right; unset key
plot 'run.dat' u 1:5 w l t 'cd', '' u 1:5 w readout format '%6.4f' t 'CD'$ foresight cb_readout_dumb.gp
0.55+----------+---------+----------+----------+---------+----------+
|* +----------------------+ |
0.5+ * |CD | +
| * | _ _ _ _ _ | |
| * || | _| | | | | |_| | |
0.45+ * ||_|. _| |_| |_| |_| | +
| * | | |
0.4+ * +----------------------+ +
| * |
| * |
0.35+ * ****** +
| * * ** |
| * * * ********* ***** |
0.3+ * * *** **** ************* **+
| * * ****** |
0.25+ * * +
| * * |
| * * |
0.2+ ** * +
| *** |
0.15+----------+---------+----------+----------+---------+----------+
0 20 40 60 80 100 120Text terminals
Text in the terminal
set terminal dumb size 64,18
plot 'run.dat' u 1:5 t 'cd'$ foresight cb_dumb.gp
0.55+--------+---------+--------+--------+---------cd******-+
0.5+* +
|* |
0.45+ * +
| * |
0.4+ * +
| * |
0.35+ * ***** +
| * * ** **** |
0.3+ * * *** ****** *******************+
| * ** ***** |
0.25+ * ** +
| * ** |
0.2+ ***** +
0.15+--------+---------+--------+--------+---------+--------+
0 20 40 60 80 100 120set terminal dumb writes to the standard output; set output 'plot.txt' to a file.
Unicode text in the terminal
set terminal block braille size 64,18
plot 'run.dat' u 1:5 t 'cd'$ foresight cb_block.gp
0.55⣯⠉⠉⠉⠉⠉⠉⠉⠉⠙⠉⠉⠉⠉⠉⠉⠉⠉⠉⠋⠉⠉⠉⠉⠉⠉⠉⠉⠋⠉⠉⠉⠉⠉⠉⠉⠉⠙⠉⠉⠉⠉⠉⠉⠉⠉⠉cd⢉⣉⣉⣉⣉⣉⠉⡇
0.5⣇⣇ ⢀⡇
⡇⠘⡄ ⡇
0.45⣇⡀⢣ ⢀⡇
⡇ ⠸⡀ ⡇
0.4⡧⠄ ⡇ ⠠⡇
⡇ ⢸ ⡇
0.35⡧⠄ ⠈⡆ ⡠⠒⠑⠒⢄ ⠠⡇
⡇ ⢱ ⡜ ⠱⡀ ⢀⣀⣀⣀ ⡇
0.3⡗⠂ ⠈⡆ ⡸ ⠈⠢⣀ ⢀⡠⠔⠊⠉⠁ ⠉⠉⠒⠒⠒⠤⠤⠤⠤⠔⠒⠒⠒⠒⠒⠒⠒⠒⠒⡇
⡇ ⢱ ⢠⠃ ⠉⠒⠒⠊⠁ ⡇
0.25⡏⠁ ⠈⡆ ⢠⠃ ⠈⡇
⡇ ⢇ ⢠⠃ ⡇
0.2⡏⠁ ⠈⠢⣀⠔⠁ ⠈⡇
0.15⣇⣀⣀⣀⣀⣀⣀⣀⣀⣠⣀⣀⣀⣀⣀⣀⣀⣀⣀⣄⣀⣀⣀⣀⣀⣀⣀⣀⣄⣀⣀⣀⣀⣀⣀⣀⣀⣠⣀⣀⣀⣀⣀⣀⣀⣀⣀⣄⣀⣀⣀⣀⣀⣀⣀⣀⡇
0 20 40 60 80 100 120block draws with Unicode characters of 2 x 4 dots (braille), 2 x 3 (sextants), 2 x 2 (quadrants, the default) or 1 x 2 (half). Add ansi (or ansi256, ansirgb) to draw each series in its color, in dumb as well.
Figures for a paper
A figure for one column
set terminal pdfcairo size single theme paper
set output 'cb_paper.pdf'
set xlabel "time [s]"
set ylabel "amplitude"
set key top right
plot [0:10] exp(-x/4)*cos(3*x) title "damped", exp(-x/4) dt 2 title "envelope"set terminal pdfcairo writes a PDF with gnuplot's options; size single is a paper's column, 8.5 x 6 cm (double: 17.8 x 8 cm), any size takes its units (size 8.5cm,6cm, 3in,2in, 240pt,170pt). theme paper sets 8 pt texts, 0.75 pt lines and the Okabe-Ito colors; cb_paper.pdf is the figure as the paper takes it, its fonts embedded.
Two panels across the page, in Latin Modern
set terminal pdfcairo size double theme paper serif
set output 'cb_paper_double.pdf'
set multiplot layout 1,2
set title "(a) response"
set xlabel "{/serif ω / ω_n}"
set logscale x
plot [0.1:10] 1/sqrt((1-x**2)**2 + (0.2*x)**2) title "ζ = 0.1"
set title "(b) phase"
set ylabel "φ [deg]"
plot [0.1:10] 180/pi*atan2(0.2*x, 1-x**2) title "ζ = 0.1"
unset multiplottheme paper serif sets the texts in Latin Modern Roman, the font of a LaTeX paper; size double spans both columns (cb_paper_double.pdf).
Math in the labels
# skin friction of a flat plate: math in the axis labels and the key
set terminal svg size 560,320
set output 'cb_math.svg'
set xlabel '$\mathrm{Re}_x = U x/\nu$'
set ylabel '$c_f$'
set logscale xy
set format xy '$10^{%T}$'
set key top right
plot [1e4:1e8] 0.664/sqrt(x) title '$c_f = 0.664\,\mathrm{Re}_x^{-1/2}$', \
0.0592*x**(-0.2) title '$c_f = 0.0592\,\mathrm{Re}_x^{-1/5}$' dt 2A text's $...$ runs are TeX math, set as LaTeX sets them in Latin Modern Math: Greek, scripts, \frac, \sqrt, \mathrm, operators with TeX's spacing, in every format (the PDF embeds the glyphs); see C7. Math in labels.
Labels set by LaTeX
# the gain of a damped oscillator, its labels and key set by LaTeX: \input{cb_latex.tex}
set terminal cairolatex pdf size single
set output 'cb_latex.tex'
set xlabel '$\omega/\omega_0$'
set ylabel '$|H(i\omega)|$'
set logscale y
set key top right
H(w, z) = 1/sqrt((1 - w**2)**2 + (2*z*w)**2)
plot [0:3] H(x, 0.1) title '$\zeta = 0.1$', H(x, 0.3) title '$\zeta = 0.3$' dt 2, \
H(x, 0.7) title '$\zeta = 0.7$' dt 3$ foresight cb_latex.gp && grep -F '\put' cb_latex.tex | tail -n 5
foresight: cb_latex.tex
\put(264,1967){\rotatebox{90.00}{\makebox(0,0){\strut{}$|H(i\omega)|$}}}%
\put(3901,2964){\makebox(0,0)[r]{\strut{}$\zeta = 0.1$}}%
\put(3901,2744){\makebox(0,0)[r]{\strut{}$\zeta = 0.3$}}%
\put(3901,2524){\makebox(0,0)[r]{\strut{}$\zeta = 0.7$}}%
\put(0,0){\includegraphics[width={240.94bp},height={170.08bp}]{cb_latex}}%set terminal cairolatex writes the drawing as a PDF without its texts (cb_latex.pdf) and a LaTeX picture (cb_latex.tex) that places every text, as gnuplot's cairolatex: a paper \inputs it and LaTeX sets the labels in the paper's fonts, its math included. The texts are LaTeX source ('$\zeta = 0.1$'), the tick numbers math; see C6. Labels set by LaTeX.
From Fortran
From Fortran: gaps in the data
NaN values are gaps, as gnuplot's undefined points; save writes any of the formats, - text on the standard output.
y(30:40) = ieee_value(1.0_R8P, ieee_quiet_nan) ! a missing stretch: the line breaks there
call fig%init(width=560_I4P, height=320_I4P)
call fig%plot(x, y, title='sin(x), samples 30-40 missing')
call fig%save('cb_gaps.svg')
call fig%save('cb_gaps.html')
call fig%save('-') ! text, on the standard output$ cb_gaps
1+--------------+---------------+---------sin(x), samples 30-40 missing******-+
0.8+ * ** ** * +
| ** * * * |
0.6+ * ** ** ** +
| ** * * * |
0.4+ * * * * +
| * * * * |
0.2+* * * +
|* * ** |
0+ * * +
-0.2+ * * +
| * * |
-0.4+ * * +
| * *|
-0.6+ ** +
| * |
-0.8+ * * +
| *** *** |
-1+--------------+---------------+--------------+--------------+---------------+
0 2 4 6 8 10From Fortran: fit, stats, times, annotations
fit and stats work on Fortran arrays as gnuplot's commands on files; civil_time makes times for a time axis; labels, arrows and objects are figure methods.
program cb_fortran_tools
!< Cookbook: from Fortran, a fit of an array (gnuplot's fit), its statistics (gnuplot's stats), a time axis and
!< annotations, in one figure.
use foresight, only : civil_time, figure_object, fit, fit_result, I4P, I8P, R8P, stats, stats_result
implicit none
type(figure_object) :: fig
type(fit_result) :: r
type(stats_result) :: s
real(R8P), allocatable :: h(:), e(:), t(:), cd(:)
real(R8P) :: q(2) = [1.0_R8P, 1.0_R8P]
integer(I4P) :: i
h = [(0.1_R8P / 2.0_R8P**i, i = 0, 5)]
e = 0.21_R8P * h**2 * [1.02_R8P, 0.97_R8P, 1.01_R8P, 0.99_R8P, 1.03_R8P, 0.98_R8P]
call fit(power_law, h, e, q, names=['c', 'p'], result=r)
! a run stamped every 90 s from 2024-03-01 10:00 UTC
t = [(civil_time(2024_I8P, 3_I8P, 1_I8P, 10_I8P, 0_I8P, 90.0_R8P * real(i, R8P)), i = 0, 80)]
cd = [(0.30_R8P + 0.04_R8P * exp(-real(i, R8P) / 20.0_R8P) * cos(real(i, R8P) / 4.0_R8P), i = 0, 80)]
s = stats(cd(41:))
call fig%init(width=760_I4P, height=320_I4P)
call fig%set_multiplot(rows=1_I4P, cols=2_I4P)
call fig%set_title('fit(power_law, h, e, q)')
call fig%set_logscale('xy')
call fig%set_format('%h', 'y')
call fig%set_key(position='left top')
call fig%plot(h, e, title='errors', with='points', pt=7_I4P)
call fig%plot(h, q(1) * h**q(2), title='order 2 fit', dt=2_I4P)
call fig%set_label('p = '//trim(fixed2(q(2))), 0.004_R8P, 1e-3_R8P)
call fig%next_panel()
call fig%set_title('stats(cd), a time axis, annotations')
call fig%unset_logscale()
call fig%set_format('%g', 'y')
call fig%set_time_axes('x')
call fig%set_format('%H:%M', 'x')
call fig%set_object('rectangle', [t(41), t(81)], [0.0_R8P, 1.0_R8P], system='first graph', fc='#56b4e9', &
fs='solid 0.2 noborder', layer='behind')
call fig%plot(t, cd, title='cd', lw=2.0_R8P)
call fig%plot(t(41:), [(s%y%mean, i = 41, 81)], title='mean of the last half', dt=2_I4P)
call fig%set_arrow(t(20), 0.335_R8P, t(41), s%y%mean, head='head', filled='filled')
call fig%set_label('settled', t(20), 0.338_R8P, justify='center')
call fig%save('cb_fortran_tools.svg')
contains
function power_law(x, p) result(f)
real(R8P), intent(in) :: x, p(:)
real(R8P) :: f
f = p(1) * x**p(2)
endfunction power_law
function fixed2(v) result(text)
real(R8P), intent(in) :: v
character(len=8) :: text
write(text, '(F8.2)') v
text = adjustl(text)
endfunction fixed2
endprogram cb_fortran_toolsFrom Fortran: 3D views
The 3D settings are figure methods named after gnuplot's commands: set_pm3d(lighting=...), set_contourfill, set_boxdepth, set_wall; splot takes the styles pm3d, contourfill, boxes, zerrorfill and polygons. See the library.
call fig%init(width=900_I4P, height=320_I4P)
call fig%set_multiplot(rows=1_I4P, cols=3_I4P)
call fig%set_colorbox(on=.false.)
call fig%set_title('lighting')
call fig%set_pm3d(lighting=.true., primary=0.5_R8P, specular=0.4_R8P)
call fig%splot(x, y, z, title='', with='pm3d')
call fig%next_panel
call fig%set_title('contourfill')
call fig%set_pm3d(lighting=.false.)
call fig%set_contourfill(levels=6_I4P)
call fig%splot(x, y, z, title='', with='contourfill')
call fig%next_panel
call fig%set_title('boxes and walls')
call fig%set_boxwidth(0.5_R8P)
call fig%set_boxdepth(depth=0.3_R8P)
call fig%set_pm3d(order='depthorder')
call fig%set_wall(which='y0')
call fig%set_wall(which='x0')
call fig%set_xyplane(relative=0.0_R8P)
call fig%set_yrange(min=0.0_R8P, max=2.0_R8P)
call fig%set_zrange(min=0.0_R8P, max=6.0_R8P)
call fig%splot([1._R8P, 2._R8P, 3._R8P, 4._R8P], [1._R8P, 1._R8P, 1._R8P, 1._R8P], [3._R8P, 5._R8P, 2._R8P, 4._R8P], &
title='', with='boxes', fs='solid 0.8')
call fig%save('cb_fortran_3d.svg')From Fortran: run gnuplot commands
script_object is the interpreter of the command line: scripts and single commands from the program, with errors returned, never stopped on.
call gp%init('cb_script.svg')
call gp%run_text("set terminal svg size 560,320"//new_line('a')// &
"set logscale y; plot 'run.dat' u 1:2 t 'continuity', '' u 1:3 t 'momentum'", iostat, iomsg)
if (iostat /= 0) print '(A)', iomsg
call gp%execute('set key bottom left', iostat, iomsg)
call gp%execute('replot', iostat, iomsg) ! re-reads run.dat and renders again