Is there a way to add linear fit equations and r^2 values to multiple plots?
44 views (last 30 days)
Show older comments
I have six subplots. Each is a property-property plot of pH and temperature. I would like to add the linear fit equation and r^2 value to each plot. I have used the Basic Fitting toolbox in the past to display linear fits on one plot at a time and to show the equation. I am wondering if I can add a line (or lines) to my plotting code to do this. Please see my plot (currently with one linear fit equation shown). '
Thank you so much!
0 Comments
Answers (1)
Star Strider
on 29 Aug 2019
There are many ways to do this.
Here is one:
function [slope,intcpt,Rsq] = linfit(x,y)
B = [x(:) ones(size(x(:)))] \ y(:);
ypred = [x(:) ones(size(x(:)))] * B
SSE=sum((y(:)-ypred).^2)
SST=sum((y(:)-mean(y)).^2)
Rsq = 1 - (SSE/SST);
slope = B(1);
intcpt = B(2);
end
X = rand(1, 20); % ‘X’
Y = 2*X+1 + randn(1,20)*0.1; % ‘Y’
[slope,intcpt,Rsq] = linfit(X,Y)
plot(X,Y,'.')
hold on
Ln = [min(X) 1; max(X) 1] * [slope; intcpt];
plot([min(X) max(X)], Ln', '-r')
hold off
text(0.7, 0.8, sprintf('R^2 = %.3f', Rsq))
The code outside the function tests it and demonstrates its use. If you want to use it, save it as: linfit.m on your MATLAB user path, then call it as I did in the demonstration code.
3 Comments
Star Strider
on 29 Aug 2019
My pleasure!
The code I wrote was for my demonstration data. A more robust text call is:
text(min(xlim)+0.7*diff(xlim), min(ylim)+0.2*diff(ylim), sprintf('R^2 = %.3f', Rsq))
That should work for all your plots. Adjust the constants (0.7 and 0.2 here) to place it where you want it. It should be in about the same relative position in every plot.
I also just discovered that I omitted some semicolons in ‘linfit’. It should be:
function [slope,intcpt,Rsq] = linfit(x,y)
B = [x(:) ones(size(x(:)))] \ y(:);
ypred = [x(:) ones(size(x(:)))] * B;
SSE=sum((y(:)-ypred).^2);
SST=sum((y(:)-mean(y)).^2);
Rsq = 1 - (SSE/SST);
slope = B(1);
intcpt = B(2);
end
I was verifying it to be certain it did what I wanted it to do, and forgot to put them back before I posted it.
See Also
Categories
Find more on Linear and Nonlinear Regression 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!