Add 2 trendlines to scatter plot
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi, I want to make a scatter plot and then add a liner fit line as well as a exponential fit line to the scatter plot and display the equations on on the plot.
I know how to plot the exponential fit line using:
x = SZA15(:,9);
y = SZA15(:,5);
f = fit(x,y,'exp1')
plot(f,x,y)
but I am not sure how to do the linear fit line.
댓글 수: 1
dpb
2017년 6월 28일
Not sure if you got this far where the problem is...
f2 = fit(x,y,'poly1');
hold all
plot(f2,x,y)
should do it, doesn't it?
채택된 답변
Mishaal Aleem
2017년 6월 28일
Similar to how you use the fit command to find the exponential fit, you can use it to find the linear fit by using 'poly1' as the fitType argument. Please see the fitType section of the fit documentation for information.
To display the equations on on the plot, you can implement this workaround from a similar MATLAB Answers question.
Assuming you would like to display the equation in the plots legend, please try the below code:
x = SZA15(:,9);
y = SZA15(:,5);
fits{1} = fit(x,y,'exp1'); %Exponential Fit Model
fits{2} = fit(x,y,'poly1'); %Linear Fit Model
hold on
plot(x,y,'o'); %Plot raw data as circles
plot(fits{1},'r');
plot(fits{2},'b');
str = {'Data'};
%Extact the equations
for i = 1:numel(fits)
% Generate the equation for each fit
eq = formula(fits{i}); %Formula of fitted equation
parameters = coeffnames(fits{i}); %All the parameter names
values = coeffvalues(fits{i}); %All the parameter values
for idx = 1:numel(parameters)
param = parameters{idx};
l = length(param);
loc = regexp(eq, param); %Location of the parameter within the string
while ~isempty(loc)
%Substitute parameter value
eq = [eq(1:loc-1) num2str(values(idx)) eq(loc+l:end)];
loc = regexp(eq, param);
end
end
str{i+1} = eq; %append fit equation
end
legend(str); %display equations in legend
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!