# In a ListPlot of LinearModelFit, Fill to the regression line

In the help for LinearModelFit, the regression line can be added to the scatter plot like this:

Show[ListPlot[data], Plot[lm[x], {x, 0, 5}]]


Is it possible to fill from the points to the regression line? This can illustrate the distance whose sum of squares is being minimized. I tried variations on this:

Filling -> Table[ lm[data[[i]][[2]]],  {i, Length[data]}]]


Here the Table will be a list of predicted values for y at each observation of x, but this results in the error "not a valid filling specification."

Maybe something like this:

data = Table[{x, .5 + .5 x + RandomReal[{-.5, .5}]}, {x,
RandomReal[7, 100]}];
lm = LinearModelFit[data, x, x];
ListPlot[{data, Table[{x,lm[x]}, {x, 0, 7, .1}]}, Joined -> {False, True},
Filling -> 1 -> {2}]


Another way, using the properties of LinearModelFit, and a convoluted way for constructing lines (note that all the plot is done with only one ListLinePlot)

verba = Table[{x, .5 + .5 x + RandomReal[{-.5, .5}]}, {x, RandomReal[7, 100]}];
lm = LinearModelFit[verba, x, x];
res = Transpose@{verba[[All, 1]], lm["PredictedResponse"]};
ListLinePlot[Flatten[Transpose@{res, verba, res}, 1], Mesh -> All, Frame -> True]


• (+1) could also use lm["PredictedResponse"] instead of #[[2]] - lm["FitResiduals"] when defining res.
– kglr
Sep 30, 2012 at 22:13
• @kguler thanks! Edited. Sep 30, 2012 at 22:23

Another possibility, using ErrorBar :

Needs["ErrorBarPlots"]

data = Table[{x, .5 + .5 x + RandomReal[{-.5, .5}]}, {x,
RandomReal[{-5, 5}, 20]}];lm = LinearModelFit[data, x, x];

dataAndError = {#, ErrorBar[(-#[[2]] + lm[#[[1]]]) {Boole[#[[2]] >= lm[# [[1]]]] , Boole[#[[2]] < lm[#[[1]]]] }]} & /@ data;

Show[Plot[lm[x], {x, -5, 5}, PlotStyle -> {Red}], ErrorListPlot[dataAndError]]


One may simply draw them as follows. This is the list of data:

lst = Table[{i, 0.5 + 0.5*i^(1/2) + RandomReal[{-.5, .5}]}, {i, 1, 10}]


This is the fitting:

ft = FindFit[lst, a*x^(1/2) + b, {{a, 0.4}, b}, x]


And this draws the fitting function together with the list and draws lines from the points specified by the list to the curve:

f[x_] := a*x^(1/2) + b /. ft
lst1 = Transpose[lst][[1]];

Show[{ListPlot[lst, PlotStyle -> Red], Plot[f[x] /. ft, {x, 0, 10}],

Graphics[
{Pink, Line[Transpose[{lst, Transpose[{lst1, Map[f, lst1]}]
}]]} ]}]


That is the outcome:

• lst1 = Transpose[lst][[1]]; can also be done this way: lst1 = lst[[All, 1]]; Oct 1, 2012 at 12:18

Yet another possibility, using Arrow[]+Arrowheads[]:

(* for reproducibility *)
BlockRandom[SeedRandom[42, Method -> "Legacy"];
data = Sort[Table[{x, .5 + .5 x + RandomVariate[NormalDistribution[]]/5},
{x, RandomReal[7, 100]}]]];

lm = LinearModelFit[data, x, x];

Show[Graphics[{ColorData[1, 1],
`