1

I want to use plot3 with varying colors as the array index progresses.

I have 3 variables: x, y, z. All of these variables contain values in the timeline progress.

For example:

x = [1, 2, 3, 4, 5];
y = [1, 2, 3, 4, 5];
z = [1, 2, 3, 4, 5];
plot3(x, y, z, 'o')

I'd like to see a change of color from (x(1), y(1), z(1)) to the last value in the plot (x(5), y(5), z(5)). How can I change this color dynamically?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
user3668129
  • 4,318
  • 6
  • 45
  • 87

1 Answers1

5

The way to go here, in my opinion, is to use scatter3, where you can specify the colour value explicitly:

scatter3(x,y,z,3,1:numel(x))

where 3 would be the size argument and 1:numel(x) gives increasing colours. Afterward you can choose your colour map as usual.

enter image description here

Using plot3 you could do the same, but it requires a loop:

cMap = jet(numel(x));  % Generates colours on the desired map

figure
hold on  % Force figure to stay open, rather than overwriting
for ii = 1:numel(x)
    % Plot each point separately
    plot3(x(ii), y(ii), z(ii), 'o', 'color',cMap(ii,:))
end

enter image description here

I'd only use the plot3 option in case you want successively coloured lines between elements, which scatter3 can't do:

cMap = jet(numel(x));  % Generates colours on the desired map

figure
hold on  % Force figure to stay open, rather than overwriting
for ii = 1:numel(x)-1
    % Plot each line element separately
    plot3(x(ii:ii+1), y(ii:ii+1), z(ii:ii+1), 'o-', 'color',cMap(ii,:))
end
% Redraw the last point to give it a separate colour as well
plot3(x(ii+1), y(ii+1), z(ii+1), 'o', 'color',cMap(ii+1,:))

enter image description here


NB: tested and exported images on R2007b, cross-checked the syntax with R2021b docs

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 2
    For the last part: if you want the color to _gradually_ change you can use the trick [here](https://www.mathworks.com/matlabcentral/answers/5042-how-do-i-vary-color-along-a-2d-line): `surface([x; x],[y; y],[z; z],[1:numel(x); 1:numel(x)], 'facecol','no','edgecol','interp','linew',1.5)` – Luis Mendo Nov 08 '21 at 15:44
  • 1
    yes to the trick above, and/or you can use any of the answer to this question: [Change color of 2D plot line depending on 3rd value](https://stackoverflow.com/q/31685078/3460361) – Hoki Nov 09 '21 at 10:12