8

I have a set of data that contains 3d Cartesian points (x, y, z) and a time stamp.

I would like to plot this data as a connected line in 3d space with the line colour changing based on the time stamp value.

Effectively i want to show the time difference in a colorbar.

Does anyone know of a way to do this?

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • related question: [Plotting multi-colored line in Matlab](http://stackoverflow.com/q/2444575/97160) – Amro Aug 07 '12 at 23:25

1 Answers1

14

Consider the following example of a 3D point moving along a helix-shaped path over time:

%# data
t = linspace(0,8*pi,200);
x = 20*t; y = cos(t); z = sin(t);

%# plot 3D line
plot3(x,y,z)
axis tight, grid on, view(35,40)

Now if you want to draw a multi-colored line, the naive solution would be to write a for-loop, drawing each small segment as a separate line, each having a different color. This is because a single line object can only have one color.

A better approach is to use a surface graphics object:

c = 1:numel(t);      %# colors
h = surface([x(:), x(:)], [y(:), y(:)], [z(:), z(:)], ...
    [c(:), c(:)], 'EdgeColor','flat', 'FaceColor','none');
colormap( jet(numel(t)) )

The result:

screenshot

Amro
  • 123,847
  • 25
  • 243
  • 454
  • It's one of those plotting tricks you learn over time ;) A quick Google search reveals several mentions of this: [cline](http://www.mathworks.com/matlabcentral/fileexchange/14677-cline) (using patches), [How do I vary color along a 2D line?](http://www.mathworks.com/matlabcentral/answers/5042-how-do-i-vary-color-along-a-2d-line), [Multi-colored lines in GNU Octave/MATLAB](http://www.inductiveload.com/posts/multi-colored-lines-in-gnu-octavematlab/) – Amro Aug 07 '12 at 23:29
  • Thanks, I googled but the answer wasn't in here so I thought it may as well be :) – Fantastic Mr Fox Aug 08 '12 at 03:56