Gnuplot linear fit with f(x) = a*x

Viewed 288

I have a following dataset:

0 6
25 27 
91 25
160 21
190 32
335 28

How to plot a linear regression in form y=ax + 6 so that the line would contain point (0,6)? I tried the following code:

f(x) = a*x +6
fit f(x) "data.txt" u 1:2 via a
plot "data.txt" u 1:2 w p pt 7, f(x) w l

Sum of distances of upper points is larger than distances of lower points (in fact we see only one lower point: (335,28) ). How to fit f(x) so that the sum of distances would be equal?

plot

1 Answers

Fitting with gnuplot is a least-square fit, i.e. the algorithm minimizes the sum of the squares of the differences between the data points and f(x) (check help fit).

In contrast, apparently you are looking for summing up the differences between data points and f(x) and trying to make the sum zero. That's not the same.

As long as your function is as simple as a*x+b you can use stats to calculate the slope of your line as you expected.

Code:

### different ways of "fitting"
reset session

$Data <<EOD
0 6
25 27 
91 25
160 21
190 32
335 28
EOD

b = 6
f(x) = a0*x + b

# least square fit
set fit nolog quiet
fit f(x) $Data u 1:2 via a0

# make sum of difference to h(x) to zero
stats $Data u 1:2 nooutput
h(x) = a1*x + b
a1 = (STATS_sum_y - STATS_records*b)/STATS_sum_x

set key top left

plot $Data u 1:2 w p pt 7, \
     f(x) w l ti sprintf("Least square fit: f(x)=a0*x+b, a0=%g",a0), \
     h(x) w l ti sprintf("Sum of differences to zero: h(x)=a1*x+b, a1=%g",a1), \
     $Data u 1:2:(0):(h($1)-$2) w vectors lc "red" nohead ti "Differences to h(x)"
### end of code

Result:

enter image description here

Related