How can I plot multiple discontinuous segments in different colors without using a for loop?

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.

 Accepted Answer

Tara - does your data set already have the NaN in it or are you constructing the x and y above with NaN inserted to indicate discontinuity? Or can you reformat the data however you want? For example, if I do
x = [1 3 5 7; 2 4 6 8];
y = [8 6 4 2; 7 5 3 1];
figure();
plot(x, y)
where each column of the x and y matrices belongs to the same data set, then I can get each segment coloured differently.

2 Comments

Tara, if it's possible to put your (x,y) coordinates into a matrix like this, this solution is more efficient than my surface proposal.
Yes, I am able to take out the NaNs, so I went with this one.

Sign in to comment.

More Answers (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)
Afterwards, you can select the colormap . For example ()
colormap('hsv')

Community Treasure Hunt

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

Start Hunting!