以对数标度绘制趋势线

时间:2013-01-06 09:40:08

标签: matlab trendline

我正在尝试将趋势线添加到semilogx图,但无法成功。我想要y(17)y(20)之间的趋势线,但不会将其绘制为直线。

这是我的代码:

%// Define equation.
x = [90868 68151 45434 34076 27261 13631 6816 3408 2273 1948 1705 1137 853 683 569 455 342 274 228 190]; 
y = [3680 3723 3800 3866 3920 4103 4250 4320 4340 4344 4350 4364 4373 4379 4384 4393 4398 4402 4405 4407];

%// Plot it
semilogx(x,y, 'bo-', 'LineWidth', 3); 
grid on; 

%// Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);

%// Give a name to the title bar. 
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')

%// Fit the y data range with a line (limitedRange).
limitedRange = 17:20;
coeffs = polyfit(x(limitedRange), y(limitedRange), 1);
xFitting = linspace(200, 90000, 50);
yFitted = polyval(coeffs, xFitting);

%// Plot the fitted line over the specified range.
hold on;
plot(xFitting, yFitted, 'ro-', 'LineWidth', 2);
legend('Original Data', 'Line Fit');

如何将趋势线显示为一条线?

1 个答案:

答案 0 :(得分:3)

这里不应该抱怨polyfit,它有效。

这是你的情节:

enter image description here

一切都有道理。你的线被扭曲的原因是因为你的x轴有一个对数刻度(如果你在对数x刻度上绘制一条线ax+b,你会看到它是alogx+b曲线)

要将其视为对数x轴上的线,您需要引入适当的“反”失真。在您的情况下,趋势线应如下计算:

limitedRange = 17:20;
coeffs = polyfit(log10(x(limitedRange)), y(limitedRange), 1); %// Note the log10
xFitting = linspace(200, 90000, 50);
yFitted = polyval(coeffs, log10(xFitting));                   %// Note the log10

这不是全部。在对数标度中,低x坐标往往更加间隔开,并且趋势线圆在x轴的较高值处将更加密集。为了否定这一点,您需要xFitting中的点在线性刻度上呈指数间隔,以便它们在对数刻度上呈线性间隔,例如:

xFitting = 10 .^ (1:.1:5);

或使用内置的logspace功能:

xFitting = logspace(1, 5, 50);

计算趋势线的最终代码应为:

limitedRange = 17:20;
coeffs = polyfit(log10(x(limitedRange)), y(limitedRange), 1);
xFitting = logspace(1, 5, 50);
yFitted = polyval(coeffs, log10(xFitting));

这应该给你以下情节:

enter image description here

再次,请记住,这是一个对数刻度!

希望这会有所帮助:)