Gnuplot 线性拟合 f(x) = a*x
Gnuplot linear fit with f(x) = a*x
我有以下数据集:
0 6
25 27
91 25
160 21
190 32
335 28
如何绘制形式为 y=ax + 6
的线性回归,以便直线包含点 (0,6)
?我尝试了以下代码:
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
上点的距离之和大于下点的距离(实际上我们只看到一个下点:(335,28))。如何拟合 f(x) 使距离之和相等?
与 gnuplot 的拟合是 least-square 拟合,即算法最小化数据点与 f(x)
之间差异的平方和(检查 help fit
)。
相比之下,显然您正在寻找总结数据点与 f(x)
之间的差异并试图使总和为零。那不一样。
只要您的函数像 a*x+b
一样简单,您就可以使用 stats
来计算您预期的直线斜率。
代码:
### 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()-) w vectors lc "red" nohead ti "Differences to h(x)"
### end of code
结果:
我有以下数据集:
0 6
25 27
91 25
160 21
190 32
335 28
如何绘制形式为 y=ax + 6
的线性回归,以便直线包含点 (0,6)
?我尝试了以下代码:
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
上点的距离之和大于下点的距离(实际上我们只看到一个下点:(335,28))。如何拟合 f(x) 使距离之和相等?
与 gnuplot 的拟合是 least-square 拟合,即算法最小化数据点与 f(x)
之间差异的平方和(检查 help fit
)。
相比之下,显然您正在寻找总结数据点与 f(x)
之间的差异并试图使总和为零。那不一样。
只要您的函数像 a*x+b
一样简单,您就可以使用 stats
来计算您预期的直线斜率。
代码:
### 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()-) w vectors lc "red" nohead ti "Differences to h(x)"
### end of code
结果: