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

18 visualizaciones (últimos 30 días)
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-+')

Respuestas (2)

Star Strider
Star Strider el 26 de Abr. de 2018
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 el 27 de Mzo. de 2025
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

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by