Plotting Scatter Plots and Linear Fittings with MATLAB: A Comprehensive Guide

Plotting Scatter Plots and Linear Fittings with MATLAB: A Comprehensive Guide

MATLAB provides an array of functions for creating scatter plots and fitting linear models to them. In this article, we will explore how to create added variable plots using plotAdded as well as fit linear regression models to a scatter graph using fitlm and other functions.

Added Variable Plots with plotAdded

An added variable plot, also known as a partial regression leverage plot, illustrates the incremental effect on the response of specified terms caused by removing the effects of all other terms. This type of plot is useful for understanding how each term in a linear model contributes to the overall prediction.

To create an added variable plot using plotAdded, you can specify a single term or multiple terms. For example, consider creating an added variable plot for the first predictor variable x1. You can fit the response variable y and the selected predictor variable x1 to all predictors except x1.

yi = gy(x2i, x3i, ..., xpi) + ryi,
x1i = gx(x2i, x3i, ..., xpi) + rxi,

where gy and gx are the fits of y and x1, respectively, against all predictors except the selected predictor (x1). The residual vectors are ry and rx.

The adjusted value is the sum of the average value and the residual for each observation. You can then plot a scatter plot of (x˜1i, y˜i), a fitted line for as a function of x˜1 (that is, β1x˜1), and the 95% confidence bounds of the fitted line.

Fitting Linear Regression Models with fitlm

To fit a linear regression model to a scatter graph using fitlm, you can specify the predictor variables and the response variable. For example:

mdl = fitlm(tbl, 'Mass~Length');
coefs = mdl.Coefficients.Estimate;
plot(length, mass, 'o')
hold on
refline(coefs(2), coefs(1));

Alternatively, you can use polyfit to estimate the coefficients and then plot the regression line:

nanIdx = isnan(length) | isnan(mass);
coefs = polyfit(length(~nanIdx), mass(~nanIdx), 1);
refline(coefs);

Visualizing Model Effects with plotSlice

If you want to look at the effects of each predictor, you can use plotSlice. This function allows you to plot the partial residuals for each term in the model.

plotSlice(mdl)

Predicting New Y Values with predict

If you want to predict new y values given a set of x-values, you can use predict.

ypred = predict(mdl, Xnew);
plot(Xnew, ypred);

Plotting Multiple Regression Lines with fitnlm

Finally, if you want to plot multiple regression lines while holding all but one term constant, you can use fitnlm.

mdl = fitnlm(tbl, 'Mass~Length+Weight');
coefs = mdl.Coefficients.Estimate;
refline(coefs);

In this article, we have explored the various ways to create scatter plots and fit linear regression models using MATLAB. By mastering these functions, you can gain a deeper understanding of your data and make more informed predictions.

Leave a comment