Effacer les filtres
Effacer les filtres

Add 2 trendlines to scatter plot

3 vues (au cours des 30 derniers jours)
David du Preez
David du Preez le 28 Juin 2017
Commenté : dpb le 28 Juin 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')
but I am not sure how to do the linear fit line.
  1 commentaire
dpb le 28 Juin 2017
Not sure if you got this far where the problem is...
f2 = fit(x,y,'poly1');
hold all
should do it, doesn't it?

Connectez-vous pour commenter.

Réponse acceptée

Mishaal Aleem
Mishaal Aleem le 28 Juin 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
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);
str{i+1} = eq; %append fit equation
legend(str); %display equations in legend

Plus de réponses (0)


En savoir plus sur Linear and Nonlinear Regression dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by