MATLAB Answers

Plot line of best fit for semilog plot

조회 수: 93(최근 30일)
William Gray
William Gray 2020년 5월 1일
댓글: Star Strider 2020년 5월 1일
Hi everyone,
So I have seen a few answers on here similar to the question I am asking but I cannot seem to apply the solutions sucessfully.
The code here is with made up numbers but the magnitude of jump between the data is reprasentative of the real thing.
PM on the x-axis increases linearly but RS on the Y-axis does not. I have applied a log scale to the y-axis and attempted to fit a line of best fit but the line is not sitting well with the data and I get a 'negative values ignored' warning?
Any help much appreciated!!
RS = [1, 0.2, 0.15, 0.1, 0.05];
PM = [1, 2, 3, 4, 5];
pmS = polyfit(PM,log(RS),2);
rs = polyval(pmS,PM);
figure('Units', 'pixels', ...
'Position', [100 200 500 375]);
hold on
sfitRS = line(PM,RS);
set(sfitRS,...
'LineStyle','none',...
'Marker','o',...
'MarkerSize',10,...
'MarkerEdgeColor',[0.3 0.3 0.3])
hold on
LOBF = plot(PM,rs); %line of best fit
set(gca, ...
'XMinorTick' , 'on' , ...
'YMinorTick' , 'on' , ...
'XGrid' , 'on' , ...
'YGrid' , 'on' , ...
'YScale' , 'log' , ...
'LineWidth' , 1 );
  댓글 수: 1
jessupj
jessupj 2020년 5월 1일
if anything you've plotted in 'regular' coordinates has negative y values, imposing a log scale on the yaxis in effect is attempting to take the logarithm of negative numbers.
it looks like your line of best fit is already logarithmically transformed, since your pmS is fit to the log of the numbers.
look at:
plot(PM,log(RS),'ok','MarkerSize',10,'MarkerEdgeColor',[0.3 0.3 0.3])
hold on
plot(PM,rs); %line of best fit

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2020년 5월 1일
It is not generally appropriate to transform possibly noisy data and then attempt to do a linear fit on it (polyfit does linear fitting), since the assumption is that the errors are normaly distributed. The logarithmic transformation makes them instead lognormally distributed, and multiplicative rather than additive.
Try this instead:
RS = [1, 0.2, 0.15, 0.1, 0.05];
PM = [1, 2, 3, 4, 5];
f = @(b,x) exp(b(1)) .* exp(b(2).*x) + b(3); % Exponential Fit With Y-Offset
B = fminsearch(@(b) norm(RS - f(b,PM)), [1; 1; 1]); % Estimate Parameters
figure
plot(PM, RS, 'p')
hold on
plot(PM, f(B,PM), '-r')
hold off
grid
.
  댓글 수: 2
Star Strider
Star Strider 2020년 5월 1일
The polyfit function does a linear least squares fit. That some of the x-variables are raised to powers to produce polynomials does not change that.
The nonlinear fit I propose correctly models the data presented.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by