2017-06-05 560 views
4

假設您有1000個索引數據點,兩個標籤分組爲region1和region2。下面是如何產生這樣的隨機數據Matlab繪圖:刪除斷開區域之間的連接線?

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,或者看起來類似於此。

回答

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

+0

太好了,這確實是我在找的東西。 –

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(:)); 

在這裏,我用不應該通過繪製作爲0Inf,由於@rdivide劃分值建設x矩陣。結果如下。

Region Plotting Example

我希望這將是一個人的未來有幫助的。