Gnuplot Function Plot Examples

Plotting built-in and user-defined functions is gnuplot’s oldest job — this page collects three small, complete function-plot examples that between them cover most everyday needs.

set title "sin(x) and cos(x)"
set xlabel "x"
set ylabel "y"
set xrange [-2*pi:2*pi]
set grid
plot sin(x) with lines linewidth 2 title "sin(x)", \
     cos(x) with lines linewidth 2 title "cos(x)"

How the script works

Example 1 (above) plots two functions in one plot command, separated by a comma. Both share the same axes and range; each gets its own legend entry from its title clause. Setting xrange to exactly two periods keeps the picture tidy.

Example 2: growth and its inverse

set title "exp(x) and log(x)"
set xlabel "x"
set ylabel "y"
set xrange [-2:3]
set yrange [-3:12]
set grid
plot exp(x) with lines linewidth 2 title "exp(x)", \
     log(x) with lines linewidth 2 title "log(x)"

Example 2 pairs a function with its inverse. Note the explicit yrange: exp(x) grows fast and would otherwise squash log(x) flat, and log(x) is only defined for positive x, so gnuplot simply draws nothing where x is zero or negative — expected behavior, not an error.

Example 3: comparing polynomials

f1(x) = x
f2(x) = x**2 / 4
f3(x) = x**3 / 20
set title "Powers of x, Scaled"
set xrange [-4:4]
set yrange [-4:4]
set grid
plot f1(x) with lines linewidth 2 title "x", \
     f2(x) with lines linewidth 2 title "x^2 / 4", \
     f3(x) with lines linewidth 2 title "x^3 / 20"

Example 3 defines user functions f1, f2, f3 before plotting them. Defining functions by name keeps the plot line readable and lets you reuse the same expression in a fit or a second figure. The divisors (4 and 20) scale the faster-growing powers so all three curves fit one window — scaling for comparison is a normal part of function plotting.

Run it online: Paste this script into the online terminal and run it — no install needed.

Variant to try

Combine the ideas: define a damped wave once, g(x) = exp(-0.2*x) * sin(x), then plot it with its envelope curves in one command: plot g(x) with lines linewidth 2 title "damped", exp(-0.2*x) with lines dashtype 2 title "envelope", -exp(-0.2*x) with lines dashtype 2 notitle. The same define-then-plot pattern scales to any formula you can write in one line.

Related tutorials: Your First Gnuplot Plot, Axis Ranges, Tics and Log Scales. See more copy-and-run scripts in the Gnuplot Examples index.

The example on this page was written for Gnuplot.xyz.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *