Home > Enterprise >  Colormap and colorbar for 3d trajectory. (Matlab)
Colormap and colorbar for 3d trajectory. (Matlab)

Time:04-27

I'm looking to do something similar to the below image (enter image description here

I can plot the sphere easily with the help of built-in functions sphere and mesh, and I can draw the trajectory with plot3. To generate the x-values I can use something like

x = tan((-1:0.01:1)*pi/2);

which gives a distribution of points fitting for the types of functions m(x) will be (most of the action will be around x = 0).

The tricky part is the color. I have looked at the colormap and colorbar built-ins, but both seem to pertain to meshes and surfaces rather than curves, so I don't see an obvious way to adapt it to my use case.

Does anyone have any ideas for how I might proceed?

CodePudding user response:

When using plot it is not possible for one line to be multicoloured. In order to make one line multicoloured, you must plot each individual segment and then colour them individually. For example:

% make some dummy data
% note that this is in the form of 1 x N row vectors
t = -.99:0.01:0.99;
x = cos(t * pi/2); 
y = sin(t * pi/2);
z = t;

% reorder data in order to plot individual line segments
indices = [1:length(x) - 1; 2:length(x)];
figure; 
p = plot3(x(indices), y(indices), z(indices), 'LineWidth', 2);
set(p, {'Color'}, num2cell(parula(length(x) - 1), 2)); % see what happens when you comment out this line

You can change the colormap you want by changing the parula keyword above. You can use any of the supplied colormaps, or create your own (in the form of an M x 3 RGB triple matrix).

You can then add the colorbar (note that these are dummy values).

c = colorbar;
caxis([-6 6]);
set(c, 'Ticks', [-6, -4, -2, -1, 0, 1, 2, 4, 6]);
set(c, 'TickLabels', {'-\infty', '-4', '-2', '-1', '0', '1', '2', '4', '\infty'});

CodePudding user response:

You can achieve a somewhat similar, but different, effect using scatter3(). It is similar to plot3() but will allow you to set color (and size, if you wish) for each data point that it plots. If the aesthetics suit you, it is a simple and versatile approach.

  • Related