Matlab图:删除断开连接区域之间的连接线?

时间:2017-06-05 16:31:22

标签: matlab plot

假设您有1000个索引数据点,其中两个标签分组为region1和region2。以下是如何生成此类随机数据的示例

indices = 1:1000;
data = zeros(size(indices));

% some regions of data
region1 = [50:100 200:340 450:500 670:980];
region2 = setdiff(indices, region1);

% generating random data
data(region1) = rand(size(region1)) + 1;
data(region2) = rand(size(region2));

现在,如果我绘制这两个区域,我会得到如下图 enter image description here

生成情节的代码

% plotting
figure(1);
cla(gca);
hold on;
plot(region1, data(region1));
plot(region2, data(region2));
hold off;

现在的问题是:是否有一种优雅的方法可以删除断开连接的数据区域之间的连接线,而无需进行太多数据操作?我仍然想使用实线linestyle,或者看起来类似于它。

2 个答案:

答案 0 :(得分:3)

如果将x或y值设为NaN,则不会绘制它们。由于您有两个免费区域,因此您可以使用它们将值设置为NaN ...

% Two vectors which each cover ALL elements in "data", but with NaN where
% the other region is to be plotted. As per example, indices=1:1000;
r1 = 1:1000; r1(region2) = NaN;
r2 = 1:1000; r2(region1) = NaN;
% Plot all data for both lines, but NaNs wont show.
figure(1); clf;
hold on;
plot(r1, data);
plot(r2, data);
hold off;

输出:

output

答案 1 :(得分:0)

如果您将区域表示为与xy长度相同的向量,其中整数值表示区域的索引(例如regions = [1 1 1 2 2 1 1 1 ..]),则会优雅单线性,为任意数量的区域完成工作。这是一个例子

% Generating test data
x = 1:1000;
y = sin(x/100) + rand(1, 1000);
regions = repelem([1 2 3 1 2 3 1 2 3 3], repelem(100, 10)); % a [1 x 1000] vector

% Plotting
plot(bsxfun(@rdivide, x(:), bsxfun(@eq, regions(:), unique(regions(:))')), y(:));

在这里,由于x除以Inf,我正在构建@rdivide的矩阵,其值不应为0。结果如下。

Region Plotting Example

我希望这对未来的某些人有所帮助。