# Plot the error in the curve fitting

I would like to plot the fitted model and the original data punctually. For example, I have:

data = {{1, 1}, {2, 2.5}, {3, 3}};
nlm = NonlinearModelFit[data, a x + b, {a, b}, x, Weights -> {1, 1, 1}]
Show[ListPlot[data], Plot[nlm[x], {x, 0, 7}]]


Looking at the picture, I would like to calculate (and plot) the difference between the ordinate of line and the ordinate of the data point, for each value of the abscissa.

#2 - nlm[#1] & @@@ data == nlm["FitResiduals"]


True

Plotting from x = 1 to 2

ListPlot[nlm["FitResiduals"], Filling -> Axis,
PlotRange -> {{1, 2}, Automatic}]


• Thank you! What should I do if I wanted to limit the plot to a specific range, for example for x between 1 and 2?
– Mark
Commented May 31, 2021 at 16:52
Clear["Global*"]

data = {{1, 1}, {2, 2.5}, {3, 3}};

(nlm = NonlinearModelFit[data, a x + b, {a, b}, x,
Weights -> {1, 1, 1}]) // Normal

(* 0.166667 + 1. x *)

{xmin, xmax} = MinMax[data[[All, 1]]];

Plot[nlm[x], {x, xmin, xmax},
Epilog -> {Red, Point[data],
Tooltip[
Line[{#, {#[[1]], nlm[#[[1]]]}}],
#[[2]] - nlm[#[[1]]]] & /@ data},
PlotRange -> {Automatic, {0, 3.2}},


One possibility to show the residues:

data = {{1, 1}, {2, 2.5}, {3, 3}};
nlm = NonlinearModelFit[data, a x + b, {a, b}, x, Weights -> {1, 1, 1}]
res = {#, {#[[1]], nlm[#[[1]]]}} & /@ data;
txt = Text[
NumberForm[Norm[#[[1]] - #[[2]]], 2], #[[1]] +
If[#[[2, 2]] > #[[1, 2]], -1, 1] {0, .2}] & /@ res;
Show[ListPlot[data], Plot[nlm[x], {x, 0, 7}],
Epilog -> {txt, Red, Line[res]}, PlotRange -> {{0, 4}, {0, 3.2}},
AxesOrigin -> {0, 0}]
`