1

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];

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

A combination of the two is probably best. You aren't using hankel to set the colours correctly, that's done earlier so you can just call set(gca, 'ColorOrder', col(A,:), 'NextPlot', 'replacechildren'); and then still use my plot(x,y) and skip the hankel but still get what you're calling the right colours
In the included picture of the figure, the last straight line (on the right) is not included. But I can assure you, it is really there ;)
thanks! I edited the question because I was getting an error with this test case..
Should the NaN values be omitted, or do they need a distinct color?
you can use col(A(~isnan(A)),:) instead of just col(A,:) to correctly avoid that error
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.