Wednesday 8 September 2010

Curve fitting with gnuplot

Let's say you want to fit a curve to some messy experimental data. You can do this in gnuplot using the following:


# Define the shape of the fitting function. Here, I have used the
# Gauss error function as an example
f(x) = a * erf((x-x0)/b) + c

# Give some initial estimates for the fitting parameters
a = 1600
b = 1
c = 1600
x0 = 45

# This command fits your fitting function to the
# x and y values contained in columns 1 and 2
# of the data file "row-data.dat". The fitting
# parameters are listed after the "via" keyword.
fit f(x) "row-data.dat" using 1:2 via a,b,c,x0

# Plot your scattered data and the fitted curve
# on the same axes for comparison.
plot f(x), "row-data.dat"

# Dump a table of the results to "fit-plot.dat"
set table "fit-plot.dat"
plot f(x), "row-data.dat"
unset table


So, there you have it. This gnuplot script will fit a nice neat curve to your messy data. A log of the fitting process will be saved as "fit.log" and the plotting data will be saved as
"fit-plot.dat".

Quite often, you'll need to play with the initial estimates in order to get a good fit but
usually this works first time.