Plot line of best fit for semilog plot
36 次查看(过去 30 天)
显示 更早的评论
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
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
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
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!