Describe a colormap in the legend of a plot

5 views (last 30 days)
I am plotting a spacecraft trajectory and use a colormap to visualize the acceleration Vector of the spacecraft in the first part of the trajectory.
The code looks like follow:
%setting color map for Acceleration Vector
Acc_min = floor(min(ab(ab>0))*10000000);
Acc_max = ceil(max(ab(ab>0))*10000000);
Acc_min = min(Acc_min,[],'all');
Acc_max = max(Acc_max,[],'all');
Delta_Acc = Acc_max - Acc_min;
Acc_vals = ceil(Delta_Acc);
cmap = colormap(jet(Acc_vals)); % colormap should be 'parula' or 'jet'
colval = round(abs(nor)*10000000-Acc_min); % number of different temperature color values
for i=1:nval
if colval(i) < 1
colval(i) = 1;
elseif colval(i) > Acc_vals
colval(i) = Acc_vals;
% plot accelearation vector
for i=1:2:nval-1
Acc_col = cmap(colval(i),:);
quiver3(pos(i,1),pos(i,2),pos(i,3),arrowlength*Acc(i,1),arrowlength*Acc(i,2),arrowlength*Acc(i,3),'Color', Acc_col)
Now I would like to describe the color map in the legend of the of the plot. I imagine a bar with the same color range and underneath, the actual acceleration values, for example 0.2 m/s^2 on the red end and 0.05 m/s^2 on the blue end. This is just an idea and any other recommendations how to properly label this are welcome!
Any help would be much appreciated!
Markus Reichel
Markus Reichel on 24 Jun 2022
You were right. the Ticks values were not within the caxis.
With these values it´s working but I don´t know why:
colbar1.Ticks = linspace(-0.0061, 0.0061, 3) ;
Do you know how I can shift the label of the colorbar from the right to the left?
And thank you very much for your help!

Sign in to comment.

Accepted Answer

Voss on 24 Jun 2022
values = 1000*rand(10);
box on
grid on
min_max = [min(values(:)) max(values(:))];
cmap = get(gca(),'Colormap');
n_colors = size(cmap,1);
legend_ax = axes(gcf(), ...
'Units','normalized', ...
'Position',[0.69 0.89 0.3 0.1], ...
'Box','on', ...
'Layer','top', ...
'XTick',[], ...
'YTick',[], ...
'XLim',[0 1], ...
'YLim',[0 2], ...
surface(legend_ax, ...
linspace(0,1,n_colors+1), ...
[0 1], ...
[0:n_colors; 0:n_colors], ...
t = [ ...
text(legend_ax,[0 1],[1 1],sprintfc('%.2f',min_max)); ...
text(legend_ax,0.5,1,'m/s^2') ...

More Answers (1)

John D'Errico
John D'Errico on 24 Jun 2022
Hard to put it into a legend, since legend is not designed to do that. Far easier (one line of code) to just put a title above the plot. Have it say something like "red = x (m/s^2) , blue = y (m/s^2)", where x and y are numbers of your choosing. Why make extra work for yourself when there is no gain?
  1 Comment
Markus Reichel
Markus Reichel on 24 Jun 2022
I would like to visualize this information for better interpretation. I now use colorbar() but have some problems with the labeling.
But thanks for the input!

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by