How to add regression line equation to a plot?
이전 댓글 표시
clear all
close all
clc
%linear regression
y = [4.0432,4.1073,4.0899,4.1319,4.2885,4.4305,4.5249,4.6172,4.6962,4.7235,4.5987,4.7927,4.895,4.9079];
x = [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012];
n=length(x);
xy=x.*y; %calculate the of x*y
x2=x.^2; %calculate the of x square
xplus=sum(x); %calculate the sum of x
yplus=sum(y); %calculate the sum of y
xyplus=sum(xy); %calculate the sum of x*y
x2plus=sum(x2); %calculate the sum of x square
xm=xplus/n; %calculate the mean of x
ym=yplus/n; %calculate the mean of y
b=(n*xyplus-xplus*yplus)/(n*x2plus-xplus*xplus); %calculate the b
a=ym-b*xm; %calculate the a
y1=a+b*x;
figure(1)
scatter(x,y) %make a graph of data point for i=1:n %loop to calculate summition
hold on
plot(x,y1)
hold off
dy='Total World CO2 Emission (tonnes)';
ylab = sprintf('%s ',dy);
ylabel(ylab,'FontSize',12)
dx='Year';
xlab = sprintf('%s ',dx);
xlabel(xlab,'FontSize',12)
fl='Total World CO2 Emission x Year';
tit = sprintf('%s %s ',fl);
title(tit,'FontSize',12)
Hi I want to show the line equation on plot, if its not possible at least I want to find it. What is the code for it?
채택된 답변
추가 답변 (1개)
Mitchell Thurston
2021년 12월 11일
the most simple way I know of would be to add it to the legend
you can add this to the last line of your code
legend({'Data Points',sprintf('Linear Fit y = %.2f + %.2f*x',a,b}, 'Location','best')
You can also use this built-in for line fitting
p = polyfit(x,y,1);
b = p(1); a = p(2);
카테고리
도움말 센터 및 File Exchange에서 Polynomials에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



