Add 2 trendlines to scatter plot

6 次查看(过去 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
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
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 个)

类别

Help CenterFile Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by