0
votes

I have some questions regarding data fitting in gnuplot. Suppose I have data formatted as follows (example of data: test.txt)

#   x       y           y_unc
1   0.20124531  2415.58 8.25706
2   0.20516169  2416.44 8.20651
3   0.21008456  2418.48 8.12084
4   0.21531272  2420.98 8.14102
5   0.22070909  2423.81 8.08436
6   0.2259568   2426.22 8.11353
7   0.23033106  2426.90 8.10172
8   0.23536205  2428.67 8.12772
9   0.24108887  2431.43 8.0769
10  0.24623346  2433.40 8.10201

I try to fit the data in column 2 agains column 3. Up to now I can do the fit by using the following code

 # Fitting data from file 

reset session 
set terminal qt size 800,480
set key left

FILE = 'test.txt'

# fit function

f(x) = a*x+b

fit [0.25:0.58] f(x) FILE u 2:3  via a,b

chi2=(FIT_STDFIT*FIT_STDFIT)

# setting label 
set label 1 'Fit Parameters' left at graph 0.7, graph 0.95 font "arial,15"
set label 2 sprintf("y= %.2fx + %.2f", a,b)left at graph 0.7, graph 0.90 font "arial,10"
set label 3 sprintf("a = %.2f %.2s %.2f",a,'±',a_err) left at graph 0.7, graph 0.86 font "arial,10"
set label 4 sprintf("b = %.2f %.2s %.2f",b,'±',b_err) left at graph 0.7, graph 0.82 font "arial,10"
set label 5 sprintf("ndf = %.2f ",  FIT_NDF) left at graph 0.7, graph 0.78 font "arial,10"
set label 6 sprintf("{/Symbol c}^2/ndf = %.2f ", chi2) left at graph 0.7, graph 0.74 font "arial,10"

# setting label box
set arrow 1 nohead at 0.51, 2755 to 0.75, 2755
set obj 10 rect at 0.63, 2710 size 0.25, 160
set obj 10 fillstyle empty border -1 front

# setting range
set xrange [0:0.8]
set yrange [2200:2800]
set ytics nomirror
set y2range [-50:300]
set y2tics 
set x2zeroaxis lt -1
set xlabel 'x-axis'
set ylabel 'y-axis'
set y2label 'residual'

# plotting 

plot FILE u 2:3:4 w yerr pt 7  lc rgb 'black' ti 'data',\
[0:0.58] f(x) w l lw 2 lc rgb 'red' ti 'fit',\
[0.25:0.58] FILE u 2:(f($2)-$3) pt 1 axes x1y2  ti 'residual'

# end code

and using the test data I can obtain this result:

fitting data

My main question is: is it possible to use 3rd variable, e.g. the line number in column 1, as the fitting range, instead of using the x value? For example, using [1:5] to fit the first 5 data instead of using [0.20:0.22].

Additional question regarding my code above, I plot the residual in together with the fit, but I want to limit the residual plot only within the fitted data. Using the above code, the residual is plotted for the whole data and I got warning: "Ignoring sample range in non-sampled data" when running this code. Is there any way to fix this one?

And last one, is there a simpler way to print the fit paramaters in the plot instead of using label?