0% found this document useful (0 votes)
3 views13 pages

Gnuplot Tutorial

The document is a comprehensive study guide on GNUPlot, a free and open-source graphing program for creating 2D and 3D plots. It covers the basics of using GNUPlot, including commands for plotting functions, data fitting, and exporting graphs, along with practical exam questions to test understanding. The guide emphasizes the program's lightweight nature and precise control over graphing, making it ideal for scientific research and educational purposes.

Uploaded by

suiujjh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Gnuplot Tutorial

The document is a comprehensive study guide on GNUPlot, a free and open-source graphing program for creating 2D and 3D plots. It covers the basics of using GNUPlot, including commands for plotting functions, data fitting, and exporting graphs, along with practical exam questions to test understanding. The guide emphasizes the program's lightweight nature and precise control over graphing, making it ideal for scientific research and educational purposes.

Uploaded by

suiujjh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPLETE STUDY GUIDE

GNUPlot
From zero to exam-ready — everything you need to know, explained
line by line

What is it? Why use it? How it works 2D Plots 3D Plots Polar Plots

Data Fitting Exporting Exam Questions

01
What is GNUPlot?
GNUPlot is a free, open-source, command-line driven graphing program that can draw 2D and 3D
plots of mathematical functions and data. It works on Windows, Linux, and macOS. You type
commands — it draws the graph. That's it.

Think of it like this: if Excel is a car with automatic gears, GNUPlot is a racing car with manual gears
— more powerful, faster, and completely in your control.

📅 🆓 ⚡
ORIGIN FREE & OPEN SOURCE LIGHTWEIGHT

Created in 1986 by Thomas 100% free to download and No heavy GUI. Runs even on
Williams & Colin Kelley. Still use. No license. Used in old computers. Perfect for
actively maintained and used scientific research at top batch processing hundreds of
in universities worldwide. institutions. graphs via scripts.
🔬
SCIENTIFIC GRADE

Used in Physics, Mathematics,


Engineering research papers
for publication-quality plots.

02
Why Use GNUPlot?
There are many graphing tools — Excel, MATLAB, Python matplotlib. So why GNUPlot? Here are the
real reasons:

REASON EXPLANATION

Scriptable Write a .gp script file once, run it 1000 times on different data automatically.

Lightweight No Python, no MATLAB license needed. Just one tiny program.

Precise Control Every axis, label, color, line type is under your command.

Multi-format Output Export to PNG, PDF, SVG, EPS (for research papers) easily.

Built-in Functions sin, cos, exp, log etc. work directly — no importing libraries.

Data Fitting Has a built-in fit command for least-square curve fitting.

Works with Physics Labs Perfect for plotting experiment data (from your Mechanics lab, etc.).

Key Insight: In your Physics practical exams, you often record data (time, distance, velocity) and need to
plot it with best-fit lines. GNUPlot does this in 3 commands. Excel would take 10 minutes of clicking.
03
How GNUPlot Works — The Basics

Starting GNUPlot
Open your terminal and type gnuplot. You'll see a prompt: gnuplot>. Now you can type commands.

1 Open terminal → type gnuplot → press Enter

2 You see the prompt gnuplot>

3 Type any command (like plot sin(x)) and press Enter

4 A window opens showing your graph!

The Most Important Commands

COMMAND WHAT IT DOES EXAMPLE

plot Plot a 2D graph plot sin(x)

splot Plot a 3D surface splot x**2 + y**2

set title Add a title to the graph set title "My Graph"

set xlabel Label the x-axis set xlabel "Time (s)"

set ylabel Label the y-axis set ylabel "Distance (m)"

set xrange Set x-axis range set xrange [-5:5]

set grid Show grid lines set grid

set terminal Choose output type (screen/file) set terminal png

set output Save to file set output "[Link]"

quit Exit GNUPlot quit


04
2D Graph Plotting
2D plots are the most common. You plot functions like sin(x), x², or data from a file against x-axis
values.

Example 1: Plot a Simple Function

GNUPLOT COMMANDS

# Plot sin(x) from -pi to pi


set xrange [-3.14:3.14]
set title "Sine Wave"
set xlabel "x"
set ylabel "sin(x)"
set grid
plot sin(x)

Line-by-line explanation:
set xrange [-3.14:3.14] — tells GNUPlot to only show x from −π to +π
set title "Sine Wave" — adds a heading above the graph
set grid — draws faint grid lines (helps in reading values)
plot sin(x) — the actual command that draws the curve

Example 2: Plot Multiple Functions on Same Graph

GNUPLOT COMMANDS

set title "Trig Functions"


set xrange [-6.28:6.28]
set yrange [-1.5:1.5]
set grid
# Plot sin and cos together using comma
plot sin(x) title "sin(x)", cos(x) title "cos(x)" lt 2
The comma , separates multiple plots. lt 2 means line type 2 (different color).

Example 3: Plot Data from a File


Say you have a file [Link] with two columns: x-values and y-values.

[Link]

# x y
1.0 2.1
2.0 3.9
3.0 6.2
4.0 8.0
5.0 10.1

GNUPLOT COMMANDS

set title "Experimental Data"


set xlabel "x"
set ylabel "y"
# 'using 1:2' means use column 1 as x, column 2 as y
# 'with points' draws dots (not lines)
plot "[Link]" using 1:2 with points pt 7 title "Data"

Multicolumn Data
If your file has 3 columns (x, y, z), you can choose which columns to plot:

GNUPLOT COMMANDS

# Plot column 1 vs column 3 (skipping column 2)


plot "[Link]" using 1:3 with linespoints title "x vs z"

# 'linespoints' = both lines AND dots together


05
3D Surface Plots
3D plots are drawn using splot (surface plot). They show functions of two variables: z = f(x, y).

Why use 3D plots? In Physics, many quantities depend on two variables — like temperature distribution
on a surface, potential energy landscapes, or wave patterns. 3D plots visualize these beautifully.

Example: Simple 3D Paraboloid

GNUPLOT COMMANDS

set title "3D Surface: z = x² + y²"


set xlabel "x"
set ylabel "y"
set zlabel "z"
set hidden3d # hides lines behind the surface (makes it look solid)
splot x**2 + y**2 title "Paraboloid"

Example: Ripple Pattern (Beautiful Wave)

GNUPLOT COMMANDS

set xrange [-10:10]


set yrange [-10:10]
set isosamples 50 # how fine the mesh is (more = smoother)
set pm3d # enables color mapping on the surface
set hidden3d
splot sin(sqrt(x**2+y**2)) / sqrt(x**2+y**2) title "Ripple"

Contour Plots (Top-Down View)


A contour plot is like viewing a 3D surface from above — like a topographic map. It shows lines of
equal height (z-value).

GNUPLOT COMMANDS
set contour base # draw contours on the base (xy-plane)
set cntrparam levels 10 # 10 contour lines
unset surface # hide 3D surface, show only contours
splot x**2 + y**2

06
Polar Plots
In a polar plot, instead of (x,y) coordinates, you use (r, θ) — radius and angle. Very common in physics
for wave patterns, antenna radiation, orbits.

How to Enable Polar Mode

GNUPLOT COMMANDS

set polar # switch to polar coordinates


set angles degrees # use degrees instead of radians (optional)
set xrange [-2:2]
set yrange [-2:2]
set grid polar # show polar grid (circles + angle lines)
plot 1 + cos(t) # Cardioid — classic heart-shaped curve

❤️ 🌸 🌀
CARDIOID ROSE CURVE ARCHIMEDEAN SPIRAL

plot 1 + cos(t) plot cos(3*t) plot t (in polar)


Heart-shaped curve. Classic Petal-shaped pattern. n petals Equal spacing between turns.
example. for cos(nt).
07
Data Fitting with the fit Command
GNUPlot can automatically find the best-fit curve for your experimental data using the fit command.
This is the famous least-squares fitting.

Real Physics Use: You measured the time-period T of a pendulum for different lengths L. Theory says T =
2π√(L/g). Use fit to find g from your data!

Complete Fitting Example (Linear)

GNUPLOT COMMANDS — STEP BY STEP

# Step 1: Define your model function


# f(x) = m*x + c (a straight line)
f(x) = m*x + c

# Step 2: Give initial guesses for parameters


m = 2.0
c = 0.5

# Step 3: Fit the function to your data file


# 'using 1:2' = column 1 as x, column 2 as y
fit f(x) "[Link]" using 1:2 via m, c

# Step 4: Plot data points AND the fitted line together


plot "[Link]" using 1:2 with points title "Data", \
f(x) with lines title "Best Fit"

Fitting a Non-linear (Exponential) Curve

GNUPLOT COMMANDS

# Radioactive decay: N = N0 * exp(-lambda * t)


g(x) = N0 * exp(-lam * x)
N0 = 100
lam = 0.1

fit g(x) "decay_data.txt" using 1:2 via N0, lam


plot "decay_data.txt" u 1:2 w points, g(x) w lines

After fitting, GNUPlot prints the best-fit values of N0 and lam with uncertainties. This is publication-quality
analysis!

08
Exporting Plots to Files
By default GNUPlot shows graphs on screen. To save to a file, change the terminal and set an output
filename.

Save as PNG (most common)

GNUPLOT COMMANDS

set terminal png size 800,600


set output "my_graph.png"
plot sin(x)
set output # close the file (important!)

Save as PDF (for reports)

GNUPLOT COMMANDS

set terminal pdfcairo enhanced


set output "[Link]"
plot cos(x) title "Cosine Wave"
set output

Using GNUPlot Script Files (.gp files)


Instead of typing commands one by one, write them all in a text file (e.g., [Link]) and run it:
TERMINAL (BASH)

gnuplot [Link]

This is extremely powerful — reuse the same script on new data files without retyping everything.

09
Practical Exam Questions

🎓 External Practical Exam — GNUPlot


These questions are at the level of a university practical examination. Attempt them yourself before
checking answers.

★ Basic Level
Q1 · Easy

Write a GNUPlot script to plot the function y = x³ − 3x for x ranging from −3 to 3. Add a proper title,
axis labels, and grid. Save the output as a PNG file named [Link]. [5 marks]

Q2 · Easy

Plot sin(x), cos(x), and sin(x)+cos(x) on the same graph for x ∈ [0, 2π]. Each curve must have a
different line type and be labeled in the legend. [5 marks]

Q3 · Easy

A data file [Link] contains two columns: time (s) and velocity (m/s). Write GNUPlot commands
to plot this data as points with a title "Velocity vs Time" and appropriate axis labels. [4 marks]

★★ Intermediate Level
Q4 · Medium

You are given a data file with 3 columns: x, y, z. Using GNUPlot, plot (a) column 1 vs column 2 and
(b) column 1 vs column 3 on the same graph. Label each curve. Explain what using 1:2 means in
GNUPlot. [6 marks]

Q5 · Medium

In a simple pendulum experiment, lengths L (cm) and time periods T (s) were recorded. Write a
GNUPlot script to: (i) plot T² vs L as data points, (ii) fit a straight line through origin T² = k·L, and
(iii) determine the value of k. What physical constant can you calculate from k? [8 marks]

Q6 · Medium

Plot the 3D surface z = sin(x)·cos(y) for x ∈ [−π, π] and y ∈ [−π, π]. Enable hidden line removal and
color mapping. Also generate the corresponding contour plot. [7 marks]

Q7 · Medium

Plot the polar curve r = sin(3θ) (a 3-petal rose) in GNUPlot. Enable polar grid. Explain why this curve
has exactly 3 petals and how you would modify the command to get 5 petals. [6 marks]

★★★ Hard / Exam Level


Q8 · Hard

The cooling of a body follows Newton's Law: T(t) = T_room + (T₀ − T_room)·e^(−λt). You have
temperature vs time data in [Link]. Write a complete GNUPlot script to: (i) define this model, (ii)
fit it to the data to obtain λ, T₀, and T_room, (iii) plot data and fit together with proper labels, (iv)
save as PDF. State what each fitted parameter physically means. [10 marks]

Q9 · Hard

Write a GNUPlot script file that reads a multicolumn data file [Link] (columns: x, y, error_y),
plots the data points with error bars using using 1:2:3 with yerrorbars, fits a quadratic f(x) =
a·x² + b·x + c to the data, overlays the fit, and exports the final graph as high-resolution PNG
(1200×900). [12 marks]

Q10 · Hard

Compare GNUPlot's fit command approach to linearisation. For the power law y = A·x^n, describe
two methods to find A and n using GNUPlot: (i) direct non-linear fitting and (ii) linearisation by
taking log of both sides and plotting log(y) vs log(x) as a straight line. Write the commands for both
methods and state which is more reliable and why. [10 marks]

💡 Exam Tip: In practical exams, you will usually be given a data file. Always start by (1) reading the data,
(2) setting proper axis labels and title, (3) plotting with points first, then (4) fitting and overlaying. This approach
earns maximum marks.

10
Quick Reference Cheatsheet

COMPLETE GNUPLOT CHEATSHEET

## BASIC PLOTTING
plot sin(x) # function
plot "[Link]" u 1:2 w lp # data file
plot f(x), g(x) # multiple curves

## LABELS & APPEARANCE


set title "Title"
set xlabel "x-axis"
set ylabel "y-axis"
set xrange [-5:5]
set yrange [0:10]
set grid
set key top left # legend position

## WITH STYLES
w lines # line only
w points # dots only
w linespoints # both
w yerrorbars # with error bars

## 3D
splot x**2+y**2
set hidden3d
set pm3d
set isosamples 50
## POLAR
set polar
set grid polar
plot 1+cos(t)

## FITTING
f(x) = m*x + c
fit f(x) "[Link]" u 1:2 via m, c

## EXPORT
set terminal png size 800,600
set output "[Link]"
plot ...
set output

GNUPlot Complete Tutorial · For Academic Use · Based on University Syllabus

You might also like