编辑最小二乘线的x限制

问题描述 投票:2回答:3

我创建了两个散点图,然后使用lsline为每个绘图添加回归线。我用过这段代码:

for i=1:2
  x = ..;
  y = ..;
  scatter(x, y, 50, 'MarkerFaceColor',myColours(i, :));
end
h_lines = lsline;

但是,较暗的线远远超出该散点图中的最后一个数据点(在x = 0.3附近):

enter image description here

lsline似乎没有允许设置其水平范围的属性。在Matlab 2016a中,是否有针对两条线分别设置的解决方法?

matlab regression least-squares
3个回答
5
投票

For a single data set

这是一种解决方法而不是解决方案。 lsline在内部调用refline,它绘制了一条填充轴的线,由当前限制(xlimylim)给出。因此,您可以将这些限制更改为您想要的行,请调用lsline,然后恢复限制。

例:

x = randn(1,100);
y = 2*x + randn(1,100); % random, correlated data
plot(x, y, '.') % scatter plot
xlim([-1.5 1.5]) % desired limit for line
lsline % plot line
xlim auto % restore axis limit

enter image description here

For several data sets

在这种情况下,您可以按顺序对每个数据集应用相同的过程,但是在调用lsline时,只需要保留一个数据集;否则当你调用它来创建第二行时,它也会创建第一行的新版本(范围错误)。

例:

x = randn(1,100); y = 2*x + randn(1,100); % random, correlated data
h = plot(x, y, 'b.'); % scatter plot
axis([min(x) max(x) min(y) max(y)]) % desired limit for line
lsline % plot line
xlim auto % restore axis limit
hold on
x = 2*randn(1,100) - 5; y = 1.2*x + randn(1,100) + 6; % random, correlated data
plot(x, y, 'r.') % scatter plot
axis([min(x) max(x) min(y) max(y)]) % desired limit for line
set(h, 'HandleVisibility', 'off'); % hide previous plot
lsline % plot line
set(h, 'HandleVisibility', 'on'); % restore visibility
xlim auto % restore axis limit

enter image description here


4
投票

还有另一种解决方案:实施自己的hsline。这很简单!

在MATLAB中,对直线进行最小二乘拟合是微不足道的。给定列矢量xyN元素,b = [ones(N,1),x] \ y;是最佳拟合线的参数。 [1,x1;1,x2]*b是沿着x坐标x1x2的两个点的y位置。因此你可以写(跟随Luis' example,得到完全相同的输出):

N = 100;
x = randn(N,1); y = 2*x + randn(N,1); % random, correlated data
h = plot(x, y, 'b.'); % scatter plot
hold on
b = [ones(N,1),x] \ y;
x = [min(x);max(x)];
plot(x,[ones(2,1),x] * b, 'b-')

x = 2*randn(N,1) - 5; y = 1.2*x + randn(N,1) + 6; % random, correlated data
plot(x, y, 'r.') % scatter plot
b = [ones(N,1),x] \ y;
x = [min(x);max(x)];
plot(x,[ones(2,1),x] * b, 'r-')

2
投票

您可以使用获取定义线的点

h_lines =lsline;

h_lines(ii).XDatah_lines(ii).YData将包含2个点,用于定义每条ii=1,2线的线。使用它们创建一个线的方程,并绘制所需范围内的线。

© www.soinside.com 2019 - 2024. All rights reserved.