MATLAB Answers

# How to fit linear regression models to a scatter graph

72 views (last 30 days)
Bea Smith on 6 Apr 2016
Edited: Adam Danz on 14 Sep 2020
Ok, so I have my data in a scatter graph:
scatter(length,mass,[],gtype,'filled');
xlabel('Length (cm)');
ylabel('Weight (g)');
(colour is set by genotype, I don't think this is the best way to do it yet but I want to treat the data as one set at the moment)
I'm then creating regression models:
m1 = fitlm(tbl,'Mass~Length');
m2 = fitlm(tbl,'Mass~Length+Genotype');
m3 = fitlm(tbl,'Mass~Genotype+Length+Genotype*Length');
Now for the problem, how do I get these linear models to display onto the scatter graph ontop of the data?
What I'm trying to achieve is something like:
Eventually I will also want to display the r values and legend.

#### 0 Comments

Sign in to comment.

### Answers (1)

Adam Danz on 10 Sep 2020
Edited: Adam Danz on 14 Sep 2020
For a simple linear regression with a single predictor variable, you can plot the regression line using
mdl = fitlm(tbl,'Mass~Length');
coefs = mdl.Coefficients.Estimate; % 2x1 [intercept; slope]
plot(length, mass, 'o')
hold on
% Plot line
refline(coefs(2),coefs(1));
or, more simply,
cla()
plot(length, mass, 'o')
% Plot line
lsline
lsline can also be used to plot the simple linear regression of each group if the groups are plotted as separate objects.
or
% Get coefficients using polyfit
nanIdx = isnan(length) | isnan(mass);
coefs = polyfit(length(~nanIdx), mass(~nanIdx), 1);
% Plot line
refline(coefs);
If the model includes multiple predictors, you can use plot(mdl) or plotAdded(mdl) (same result) to create a partial regression leverage plot (aka "added variable plot"). If you want to specify the coefficients to be used in the regression line, use plotAdded(mdl,coef).
If you want to look at the effects of each predictor, use plotSlice(mdl).
If you want to plot the regression line given a new set of x-values, use ypred = predict(mdl,Xnew) to compute the new y values and then plot the results using plot(Xnew, ypred).
Or perhaps you want to plot a range of possible regression lines while holding all but one term constant. That's demonstrated here in a non-linear regression (fitnlm) demo but the same logic can be applied to the a fitlm model.
To explore your model in various visualizations developed for the fitlm output, see this workflow in the documentation.

#### 0 Comments

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!