How can I plot multiple discontinuous segments in different colors without using a for loop?
Ältere Kommentare anzeigen
I'd like to plot my data in segments using NaNs to indicate discontinuity:
x = [1 2 NaN 3 4 NaN 5 6 NaN 7 8];
y = [8 7 NaN 6 5 NaN 4 3 NaN 2 1];
figure();
plot(x, y)
which makes this:

The problem is I am not sure how to make the segments different colors without chopping the data into pieces and using a for loop (not an option with my bigger data). For this example, using the default ColorOrder is fine; I just want each segment to change to the next color in whatever the order is.
Akzeptierte Antwort
Weitere Antworten (1)
There is no way to assign >1 color to a line without breaking up the line. However, you could plot a surface instead and by making it 2D and thin, you could make it appear as a line. Here's a demo and the figure it produces.
% Your data
x = [1 2 NaN 3 4 NaN 5 6 NaN 7 8];
y = [8 7 NaN 6 5 NaN 4 3 NaN 2 1];
% Assign color based on NaN groups
col = cumsum(isnan(x));
% Make sure 3rd dimension is flat
z = zeros(size(x));
% Plot surface with thin edge to appear as line
surface([x;x],[y;y],[z;z], [col;col], 'FaceColor', 'none', ...
'EdgeColor', 'interp', 'LineWidth', 2)
colormap('hsv')

Kategorien
Mehr zu Surface and Mesh Plots finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!