
How to add line of best fit to plot?
56 views (last 30 days)
Show older comments
I want to add a line of best fit to my plot using the polyfit function. However, the graph turns blank when I integrate polyfit in my code. How can I change it to make polyfit work?
% original graph without line of best fit
rideData; % file that contains arrays of data/numbers for climb and calories
figure(1);
plot(climb, calories, "o");
xlabel('climb');
ylabel('calories');
% new graph with polyfit. it turns blank
rideData; % file that contains arrays of data/numbers for climb and calories
figure(1);
polyfit(climb, calories, "o");
xlabel('climb');
ylabel('calories');
0 Comments
Accepted Answer
Image Analyst
on 9 Dec 2018
Edited: Image Analyst
on 16 May 2020
You are not accepting the coefficients from polyfit() - they basically are thrown away. Even if you did do
coefficients = polyfit(climb, calories, 2);
you still need to compute the fitted values, like
numFitPoints = 1000; % Enough to make the plot look continuous.
xFit = linspace(min(climb), max(climb), numFitPoints);
yFit = polyval(coefficients, xFit);
hold on;
plot(xFit, yFit, 'r-', 'LineWidth', 2);
grid on;
See attached demo, which produces the plot below.

2 Comments
Noushin Quazi
on 16 May 2020
i believe the reference to polyfit in the second code blurb is meant to be polyval
Image Analyst
on 16 May 2020
Edited: Image Analyst
on 16 May 2020
Sorry - you are correct. I'll correct it. Thanks for catching that.
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!