# How can I plot a linear regression line on a loglog scatter plot in MATLAB?

36 views (last 30 days)
Samaneh Arzpeima on 8 Feb 2019
Commented: Samaneh Arzpeima on 14 Feb 2019
I have a dataset of 168rows & 2colmns, plot them with a loglog scale.Now I have to plot the regression line on it,I have no special matlab tools to use "lsline" or ...
How can we draw the regression line on a loglog plot?
I find some rows of code and tried them but didn't work.
Any help will be appreciated.
clear
clc
moment = numdata(:,6);
average_slip = numdata(:,13);
% M0=log10(moment);
% av_slip=log10(average_slip);
%
% xd=M0(:)-mean(M0);
% yd=av_slip(:)-mean(av_slip);
%
% squre_xd=xd.^2;
% squre_yd=yd.^2;
%
% xy_d=xd.*yd;
%
% Sxy=sum(xy_d);
% Sxx=sum(squre_xd);
% a=Sxy./Sxx;
% ave_point=[mean(M0);mean(av_slip)];
% b=ave_point(2)-(a*ave_point(1))
% y_hat=(b*(M0.^a))
loglog(moment,average_slip,'o')
% hold on
% % lsline
% plot(moment,y_hat)
X = [ones(length(moment),1) moment];
b = X\average_slip;
yCalc2=b(1)+moment*b(2)
loglog(moment,yCalc2,'--')

David Goodmanson on 12 Feb 2019
Hi Samaneh,
I will abbreviate moment and average_slip as x and y here. Since log log space is evidently the most meaningful representation, the fit should take place using the logs of the y and x variables. You end up with a fit log(y) = a + b*log(x). However, you want to insert this into a loglog plot which is effectively going to take the logs of whatever you input, and then plot. Therefore you have to exponentiate the fit equation. So for the fit line to plot,
yplot = exp(a+b*log(x)) = exp(a)*x^b
This says that a straight line on a loglog plot always has the form y = A*x^b.
The data is pretty scattered so the quality of the fit line is dubious, but there it is.
Going back to the linear fit for the moment, with
b = X\average_slip;
you found the fit parameters in the two-component column vector b. To create the best fit line, you don"t have to use b(1) and b(2) as you did. You can just 'undo the backslash', and find the fit line with
average_slip (fit line) = X*b
code
moment = numdata(:,6);
average_slip = numdata(:,13);
X = [ones(length(moment),1) log(moment)];
b = X\log(average_slip);
yCalc2 = X*b;
yCalc2plot = exp(yCalc2);
figure(1)
loglog(moment,average_slip,'o',moment,yCalc2plot,'+-')
Samaneh Arzpeima on 14 Feb 2019
THANK YOU SOO MUCH,right log land.
I tend to forget about it.
Now I am totally clear about the issue. tanx again.

### Categories

Find more on Surface and Mesh 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!

Translated by