How to Use Progressive Coloring with Plot3?

How to Use Progressive Coloring with Plot3?

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?

1 Answer

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.

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

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,:))

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.