删除绘图中每个数据部分之间的连接:MATLAB

时间:2017-08-17 12:35:07

标签: matlab plot matlab-figure

如下图所示,我有来自不同时间集的数据集合。但是,有一条线将每个数据部分的末尾连接到下一个数据部分的开头。

有没有办法在不改变数据的情况下抑制此连接?

enter image description here

1 个答案:

答案 0 :(得分:2)

简介

目前,MATLAB正在数组中所有连续点之间绘制线条,包括x值大幅跳跃时。

一个等效的例子就是这个情节:

% Create some x with points spaced by 0.1, except at 2 jumps of 5
x = [0:0.1:10, 15:0.1:25, 30:0.1:40];
y = sin(x);
plot(x,y)

enter image description here

注意我们的3个部分(10-15,25-30)之间的直线连接。

方法1:保持多个地块

我们可以使用finddiff来获取x跳转的区域,然后逐个绘制每个区域。

% Include indices for the first (we're going to +1, so start at 0) and last elements
% You can change this 1 to any tolerance you like, it might be of the order 10^4 for you!
idx = [0, find(diff(x) > 1), numel(x)];
% Hold on for multiple plots
hold on;
% Loop over sections and plot
for ii = 2:numel(idx)
    % Plots will loop through colours if you don't specify one, specified blue ('b') here
    plot(x(idx(ii-1)+1:idx(ii)), y(idx(ii-1)+1:idx(ii)), 'b')
end
hold off; % good practise so you don't accidentally plot more on this fig!

joined

方法2:使用NaN

您还可以使用NaN值来分解数据。 NaN值不是由MATLAB绘制的,因此如果我们在每个中断中包含一个值,则没有任何内容可以连接到该行,我们会看到中断:

% Notice the NaNs!
x = [0:0.1:10, NaN, 15:0.1:25, NaN, 30:0.1:40];
y = sin(x);
plot(x,y)

not joined

自动化:您可能希望使用diff函数动态查找某些预先存在的x的跳转,如此

% Define some x and y as before, without NaNs, with big gaps in x
x = [0:0.1:10, 15:0.1:25, 30:0.1:40];
y = sin(x);
% Create anonymous function to insert NaN at vector index 'n'
insertNaN = @(v, n) [v(1:n), NaN, v(n+1:end)];
% Get indices where gap is bigger than some value (in this case 1)
idx = find(diff(x) > 1);
% Loop *backwards* through indices (so they don't shift up by 1 as we go)
for ii = numel(idx):-1:1
    x = insertNaN(x,idx(ii));
    y = insertNaN(y,idx(ii));
end
% Plot appears the same as the second plot above
plot(x,y);

注意:如果您想对xy进行进一步处理,最好将随机NaN值添加到数组中!你可以:

  • 之后删除它们(假设没有预先存在的NaN)

    x = x(~isnan(x));
    y = y(~isnan(y));
    
  • 使用临时变量进行绘图

     xplot = x;
     % then adding NaNs to xplot for plotting ...