Add 2 trendlines to scatter plot

11 views (last 30 days)
David du Preez
David du Preez on 28 Jun 2017
Commented: dpb on 28 Jun 2017
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 Comment
dpb
dpb on 28 Jun 2017
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?

Sign in to comment.

Accepted Answer

Mishaal Aleem
Mishaal Aleem on 28 Jun 2017
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

More Answers (0)

Categories

Find more on Curve Fitting Toolbox 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!