How to show r square correlation and RMSE on a scatterplot
374 views (last 30 days)
PARIVASH PARIDAD on 5 Sep 2019
I have 2 colmuns in my excel file and I need to make the scatterplot which I wrote:
dataset = xlsread ('data.xlxs');
x = dataset (:,1);
y = dataset (:,2);
plot (x, y, '*')
Now I need to fit a linear regression line on the plot and display the Y=ax+b equation along with R square and RMSE values on the plot.
Can anyone help me? Thanks
Petter Stefansson on 5 Sep 2019
Given your x and y vectors, perhaps this is what you are looking for?
plot(x, y, '*','displayname','Scatterplot')
% Fit linear regression line with OLS.
b = [ones(size(x,1),1) x]\y;
% Use estimated slope and intercept to create regression line.
RegressionLine = [ones(size(x,1),1) x]*b;
% Plot it in the scatter plot and show equation.
plot(x,RegressionLine,'displayname',sprintf('Regression line (y = %0.2f*x + %0.2f)',b(2),b(1)))
% RMSE between regression line and y
RMSE = sqrt(mean((y-RegressionLine).^2));
% R2 between regression line and y
SS_X = sum((RegressionLine-mean(RegressionLine)).^2);
SS_Y = sum((y-mean(y)).^2);
SS_XY = sum((RegressionLine-mean(RegressionLine)).*(y-mean(y)));
R_squared = SS_XY/sqrt(SS_X*SS_Y);
fprintf('RMSE: %0.2f | R2: %0.2f\n',RMSE,R_squared)
More Answers (2)
Rik on 5 Sep 2019
With the code below you can determine a fitted value for y. Now it should be easy to calculate the Rsquare and RMSE. Let me know if you're having any issues.
f=@(b,x) b(1)*x+b(2);%linear function
OLS=@(b,x,y,f) sum((f(b,x) - y).^2);%objective least squares
opts = optimset('MaxFunEvals',50000, 'MaxIter',10000);
% Use 'fminsearch' to minimise the 'OLS' function
ABHILASH SINGH on 18 Aug 2020