How to avoid connecting data points on a plot when there is a gap in data?

18 次查看(过去 30 天)
Hi. I am trying to plot some signal data points over a profile but there is some discontinuity in the signals. I would like to only connect the data points that are continuous and wherever there is a gap avoid connecting data points.So I have data points for every 10m except for 130m and 140m. I want to avoid connecting 120 to 130.
figure(1)
hold on;
plot(Distance,Sig1,'k-o')
plot(Distance,Sig2,'k-s')
plot(Distance,Sig3,'k-d')
plot(Distance,Sig4,'k-+')

回答(2 个)

Star Strider
Star Strider 2018-4-26
Try this:
x = [20:10:120 150 160];
y = rand(3, size(x,2))*1E+4;
didx = [(diff(x) > 10) false ];
x(didx) = NaN;
y(:,didx) = NaN;
figure
plot(x, y)

David Themens
David Themens 2025-3-27
Here's a function I wrote based on the suggested solution of the other replier, which was itself a good idea. Their approach doesn't end up working correctly when you want to add multiple gaps in, since it doesn't account for the index translation caused by the prior gap filling. Instead, you have to shift everything by one additional index for every point you add. The example below is for a datetime object for the x-axis variable:
function [xnew,ynew] = insert_NaN(x,y,diffuse)
a = [false (diff(x) > diffuse)];
count = sum(a(:));
ind = 1:length(a);
ind = ind(a);
indup = (1:length(ind))-1;
ind = ind +indup;
xnew = NaT(1,length(x)+count);
ynew = zeros(1,length(x)+count);
ynew(ind) = NaN;
xnew(ind) = NaT;
xnew(~isnan(ynew)) = x;
ynew(~isnan(ynew)) = y;
end
For a non-datetime x variable, you'd instead use below (just changing NaT to zeros in the array predefinition and setting the filler value to NaN):
function [xnew,ynew] = insert_NaN(x,y,diffuse)
a = [false (diff(x) > diffuse)];
count = sum(a(:));
ind = 1:length(a);
ind = ind(a);
indup = (1:length(ind))-1;
ind = ind +indup;
xnew = zeros(1,length(x)+count);
ynew = zeros(1,length(x)+count);
ynew(ind) = NaN;
xnew(ind) = NaN;
xnew(~isnan(ynew)) = x;
ynew(~isnan(ynew)) = y;
end

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by