gabboshow
gabboshow

Reputation: 5549

plot elements of array with different colors

I have a vector of integers that vary from 1 to 4.

A=[1 2 3 4 2 3 2 1 2 3 4 4]

I would like to plot A with different colors for each value... the vertical line that links A(1) to A(2) should have the color of the first value (in this case 1).

Is that possible?

and how to handle the case of NaN present in the vector? I should plot A against a time vector

A = [1 1 1 NaN 4 4 4 Nan 2 2 3 3];
time = [1 2 3 4 5 6 7 8 9 10 11 12];

Upvotes: 1

Views: 944

Answers (2)

MeMyselfAndI
MeMyselfAndI

Reputation: 1320

Suppose you have the following set of colors:

col = hsv(4);

You set the order of the colors based on the values of A:

figure();
set(gca, 'ColorOrder', col(A,:), 'NextPlot', 'replacechildren');

Then, you can plot each line in the desired color:

n = numel(A);
plot(hankel(0:1,1:n-1),hankel(A(1:2),A(2:n)))

This results in:


Edit: The hankel approach is a bit like shooting with a bazooka to kill a mosquito, as we say in the Netherlands. Anyway, I learned about it a few questions ago - so I liked to use it. See the post of Dan for a simpler alternative for the plotting. Still, setting the correct colors can be done as in the above.

Upvotes: 2

Dan
Dan

Reputation: 45741

You can do it using just a touch of trickery:

A=[1 2 3 4 2 3 2 1 2 3 4 4]

x = [1:numel(A)-1; 2:numel(A)];
y = A(x);

plot(x,y)

enter image description here

Upvotes: 1

Related Questions