gnuplot绘图问题:数据点与拟合函数曲线不匹配
gnuplot数据点与拟合曲线不匹配问题解决
我使用gnuplot绘制函数曲线与数据点时,发现两者完全无法匹配。以下是我的绘图脚本:
set terminal svg size 600, 320 font 'Arial,10' set xlabel 'Amount' set ylabel 'Response' set grid set xrange [*:*] set yrange [*:*] set samples (100 - 1)/1 + 1 f(x) = -.00460160431126948 + (x * .159907884344821) + ((x**2) * 0) plot f(x) with lines lw 3 linecolor rgb 'purple' notitle, '-' with points ls 7 linecolor rgb 'orange' notitle 0 13.33 .2 582.23333 1 2746.95 10 26147.62333 50 131314.39667 75.000001875 192126.03 100 259905.49333 e
绘图结果显示紫色拟合曲线几乎紧贴x轴,而橙色数据点的y值远高于曲线,两者完全脱节。
问题原因
手动输入的拟合函数参数完全错误:数据呈现明显的线性关系,x=100时y≈260000,斜率大概在2600左右,但设置的斜率仅为0.16,差了四个数量级,导致曲线和数据完全不匹配。
解决方法
用gnuplot自带的fit命令自动计算拟合参数,而不是手动输入错误值。修改后的脚本如下:
set terminal svg size 600, 320 font 'Arial,10' set xlabel 'Amount' set ylabel 'Response' set grid set xrange [*:*] set yrange [*:*] # 定义线性拟合模型 f(x) = a + b*x # 初始化参数(帮助拟合快速收敛,可省略) a = 0 b = 2600 # 从标准输入拟合数据 fit f(x) '-' via a, b # 绘制拟合曲线和数据点 plot f(x) with lines lw 3 linecolor rgb 'purple' title sprintf("拟合曲线: y=%.2f + %.2fx", a, b), \ '-' with points ls 7 linecolor rgb 'orange' title '数据点' # 拟合用数据 0 13.33 .2 582.23333 1 2746.95 10 26147.62333 50 131314.39667 75.000001875 192126.03 100 259905.49333 e # 绘图用数据 0 13.33 .2 582.23333 1 2746.95 10 26147.62333 50 131314.39667 75.000001875 192126.03 100 259905.49333 e
更简洁的写法
如果不想重复输入数据,可将数据保存到单独文件(比如data.txt),脚本简化为:
set terminal svg size 600, 320 font 'Arial,10' set xlabel 'Amount' set ylabel 'Response' set grid set xrange [*:*] set yrange [*:*] f(x) = a + b*x a = 0 b = 2600 fit f(x) 'data.txt' via a, b plot f(x) with lines lw 3 linecolor rgb 'purple' title sprintf("拟合曲线: y=%.2f + %.2fx", a, b), \ 'data.txt' with points ls 7 linecolor rgb 'orange' title '数据点'
内容的提问来源于stack exchange,提问作者mhearse
相关产品推荐
相关产品推荐

