← All posts
June 20, 20242 min read
GNUplot Cheatsheet
Plotting a column against its row index, and building normalized histograms from a single-column data file.
#gnuplot#plotting
Plot a column against its row index
plot "data.txt" u ($0):4 title "Plotting with x innumeration"$0 is the line number, so this plots column 4 against its position in the file.
Column 0 is the pseudo-column $0 — the zero-based row number — so plot 'file' using 1 is equivalent to plot 'file' using 0:1.
Plot a histogram
set terminal png
set output 'histogram.png'
set style data histogram
set style fill solid
set xlabel 'Angles(°)'
set ylabel 'Normalized Frequency'
set title 'Angles distribution for α'
bin_width = 1
bin(x, width) = width * floor(x / width) + bin_width / 2.0
stats 'angles.txt' nooutput
total_points = STATS_records
plot 'angles.txt' using (bin($1, bin_width)):(1.0/total_points) smooth freq with boxes lc rgb 'blue' notitlebin_widthcontrols the sampling density (bin width).- Dividing by
total_pointsnormalizes the histogram — drop that division for an unnormalized count. angles.txtis assumed to be a single column of values.
For grouped or categorical bars, use the histograms style instead of manual binning:
set style data histograms
set style histogram clustered
plot 'file.dat' using 2:xtic(1)using 2:xtic(1) reads the bar heights from column 2 and labels each bar with the text in column 1.
Saving to a file
set terminal pngcairo size 800,600
set output 'fig.png'
# switch to PDF instead
set terminal pdfcairo
set output 'fig.pdf'After changing terminal and output, re-run plot (or replot) so the file actually gets written.
Multiple panels
set multiplot layout 2,2 # 2x2 grid, filled row-major
plot 'a.dat' using 1:2
plot 'b.dat' using 1:2
plot 'c.dat' using 1:2
plot 'd.dat' using 1:2
unset multiplotLog-scale axes
set logscale x # log x only
set logscale y
set logscale xy # both