Finding the linear regression of data and plotting it

This is for a physics report that I have to hand in. I have a list of two-dimensional data points that approximately form a linear line.

I want to:

1. calculate the best linear fit.
2. put both data points and the linear fit line on a plot
3. put names and units on x and y axis
4. (if possible) put slope and intersection of best fit on plot

Is it possible to do this in Mathematica and if so how?

Example data:

Time, Displacement

t (s)   d (m)
0       0
1       1.9
2       3.8
3       5.9
4       8.1
5       10.1

• It's all possible. Have a look at Fit, ListPlot, Plot, Show, AxesLabel and Epilog. Commented Jul 30, 2012 at 20:16

Alternatively you might consider using LinearModelFit which allows for extraction of properties such as residuals, influence measures, etc.

data = {{0, 0}, {1, 1.9}, {2, 3.8}, {3, 5.9}, {4, 8.1}, {5, 10.1}};

lm = LinearModelFit[data, x, x];


Another small change from Mr. Wizard's solution is to add the graphics options to Show rather than the individual plots. I find this cleaner in some cases.

Show[ListPlot[data], Plot[lm[x], {x, 0, 5}],
AxesLabel -> {"x-name", "y-name"}, PlotLabel -> lm["BestFit"]
]


• Another option is to use only a Plot and add the data points with Epilog->Point@data Commented Jul 30, 2012 at 21:28
• @Simon Yes. I almost used that but I decided it was more advanced than necessary in answer to a beginner's question. Commented Jul 30, 2012 at 23:28
• Thanks :) How can I fit with "y = ax" instead of "y = ax + b"? Commented Jul 31, 2012 at 21:29
• @LucyBrennan check out the help for the option IncludeConstantBasis. Commented Jul 31, 2012 at 23:18

Basically:

data = {{0, 0}, {1, 1.9}, {2, 3.8}, {3, 5.9}, {4, 8.1}, {5, 10.1}};

Block[{x},
f[x_] = Fit[data, {1, x}, x]
]


-0.119048 + 2.03429 x

Show[
ListPlot[data, AxesLabel -> {"X data", "Y data"}], (* arbitrary labels *)
Plot[f[x], {x, Min@#, Max@#}] &@data[[All, 1]]
]


I hope that this will help. The Excel table has the columns titles. I use the following code:

Clear["*"];
xlab = data[[1, 1]];
ylab = data[[1, 2]];

(* Linear model weighted *)
weight = 1/xcol^2;
model = LinearModelFit[dataDRO, x, x, Weights -> weight];
equation = Normal[model];
slope = Select[equation[[2]], # Epsilon Reals &, 1];
intercept = equation[[1]];
predicted = (ycol - intercept)/slope;

(* The table *)
accuracy = predicted*100/xcol;
qwerty = Transpose[Flatten /@ {xcol, ycol, predicted, accuracy}];
Grid[Prepend[qwerty, {xlab, ylab, "Predicted", "% Accuracy"}],
Alignment -> Right, Background -> None,
Dividers -> {All, {1 -> True, 2 -> True, -1 -> True}}]
Print["y = ", model["BestFit"]]
Print["R2 = ", model["RSquared"]]

(* The plot *)
Show[
`