How to plot result from fitnlm?

57 views (last 30 days)
Arthur Vieira
Arthur Vieira on 23 Sep 2019
Commented: Jorge Ayala Mina on 11 Jul 2021
I've fitted some data with fitnlm and am trying to plot the resulting data.
Looking at this discussion, plot(mdl) should be enough, but I get the following error:
Error using plot
A numeric or double convertible argument is expected
Short code snipet:
model = @(b,time) b(1)*(exp(-time./b(2)).*sin(2.*pi.*b(3).*time + b(4)));
b0 = [0.014 0.1 fres1 phase1];
mdl = fitnlm(time, data4, model, b0);
plot(time, data)
Hold on
plot(mdl) % Results in above error

Answers (2)

Star Strider
Star Strider on 23 Sep 2019
One way is to get the estimated parameters, then plug them into your ‘model’ function:
model = @(b,time) b(1)*(exp(-time./b(2)).*sin(2.*pi.*b(3).*time + b(4)));
b0 = [0.014 0.1 fres1 phase1];
mdl = fitnlm(time, data4, model, b0);
parms = mdl.Coefficients.Estimate; % Get Estimated Parameters
plot(time, data4)
hold on
plot(time, model(parms,time))
  1 Comment
Adam Danz
Adam Danz on 23 Aug 2020
In addition to
model = @(b,time) b(1)*(exp(-time./b(2)).*sin(2.*pi.*b(3).*time + b(4)));
parms = mdl.Coefficients.Estimate;
model(parms,time)
also see
predict(mdl,time)

Sign in to comment.


Adam Danz
Adam Danz on 23 Aug 2020
Edited: Adam Danz on 23 Aug 2020
Demo: plotting fitnlm results with two predictors
This demo supplements Star Strider's answer by showing how to plot fitnlm() results along with two predictor variables and by explaining how to interpret the results.
Two predictors (Horsepower & Weight) are used to predict fuel efficiency (miles per gallon). The predict() function is used to create the fitted lines.
Five fitted curves are plotted for each predictor variable while holding the other predictor variables constant at 5 different values.
% Load Matlab built-in dataset
load carbig
tbl = table(Horsepower,Weight,MPG);
% Create a model that predicts MPG given Horsepower & Weight of cars
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
mdl = fitnlm(tbl,modelfun,beta0);
% Plot predictor variables twice
clf()
tlo = tiledlayout(2,2);
tl(1) = nexttile(1);
plot(tbl.Horsepower, tbl.MPG, 'o', 'Color', [.5 .5 .5])
xlabel('Horsepower')
ylabel('MPG')
axis tight
hold on
tl(2) = nexttile(3);
plot(tbl.Weight, tbl.MPG, 'o', 'Color', [.5 .5 .5])
xlabel('Weight')
ylabel('MPG')
axis tight
hold on
tl(3) = nexttile(2);
plot(tbl.Horsepower, tbl.MPG, 'o', 'Color', [.598 .195 .797])
xlabel('Horsepower')
ylabel('MPG')
axis tight
hold on
tl(4) = nexttile(4);
plot(tbl.Weight, tbl.MPG, 'o', 'Color', [.598 .195 .797])
xlabel('Weight')
ylabel('MPG')
axis tight
hold on
title(tlo, 'fitnlm fit predictions','FontSize',24)
title(tl(1), sprintf('MPG as a function of Weight\nwhile holding Horsepower constant.'))
title(tl(3), sprintf('MPG as a function of Horsepower\nwhile holding Weight constant.'))
% Plot the model results predicting MPG from weight while holding HP constant.
HPvalues = [60 80 100 120 140];
colors = lines(numel(HPvalues));
fitHandles = gobjects(1,numel(HPvalues));
for i = 1:numel(HPvalues)
xPred = [ones(100,1)*HPvalues(i), linspace(min(tbl.Weight),max(tbl.Weight),100)'];
yPred = predict(mdl, xPred);
fitHandles(i) = plot(tl(2),xPred(:,2), yPred, '-', 'Color', colors(i,:), 'LineWidth', 1.5, ...
'DisplayName', sprintf('fit when HP=%d', HPvalues(i)));
xline(tl(1),HPvalues(i), '-', '', 'Color', colors(i,:), 'LineWidth', 1.5, 'Alpha', 1)
end
legend(fitHandles)
% Plot the model results predicting MPG from HP while holding Weight constant.
WTvalues = [2000 2500 3000 3500 4000];
colors = lines(numel(WTvalues));
fitHandles = gobjects(1,numel(WTvalues));
for i = 1:numel(WTvalues)
xPred = [linspace(min(tbl.Horsepower),max(tbl.Horsepower),100)', ones(100,1)*WTvalues(i)];
yPred = predict(mdl, xPred);
fitHandles(i) = plot(tl(3),xPred(:,1), yPred, '-', 'Color', colors(i,:), 'LineWidth', 1.5, ...
'DisplayName', sprintf('fit when Weight=%d', WTvalues(i)));
xline(tl(4),WTvalues(i), '-', '', 'Color', colors(i,:), 'LineWidth', 1.5, 'Alpha', 1)
end
legend(fitHandles)
For example, when Horsepower=100 and Weight=4000, MPG is 17.9. This can be seen by the yellow lines in the left plots or the green lines in the right plots. This can also be confirmed using plotSlice(mdl).
Use 2D grids of predictor values covering the entire predictor space and show the predicted results (MPG) for all combinations of predictors.
% Create grids of predictor values
x1Pred = linspace(min(tbl.Horsepower),max(tbl.Horsepower),100)';
x2Pred = linspace(min(tbl.Weight),max(tbl.Weight),100)';
[x1,x2] = meshgrid(x1Pred, x2Pred);
% Compute MPG for each pair of predictors
z = reshape(predict(mdl, [x1(:),x2(:)]),size(x1));
% Plot the results within a contour plot
figure()
contourf(x1,x2,z,'ShowText','on')
xlabel('Horsepower')
ylabel('Weight')
cb = colorbar();
ylabel(cb, 'MPG')
title('fitnlm fit predictions')
Again, we can see that when Horsepower=100 and Weight=4000, MPG is 17.9. Set the contour levels property to increase or decrease the number of contour levels.

Tags

Community Treasure Hunt

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

Start Hunting!