Home > OS >  How to use progressive coloring with plot3?
How to use progressive coloring with plot3?

Time:11-09

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?

CodePudding user response:

The way to go here, in my opinion, is to use 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

  • Related