MATLAB: How to set the label of a colorbar and tick on color division

colorbarcolormapdiscretediscrete colorbarlabel;ytickyticklabel

The next code plots a colorbar with the colors I desire
RGB=[0.384 0 0
0.525 0 0
0.717 0 0
0.741 0.168 0
0.765 0.333 0
0.765 0.525 0
0.765 0.717 0
0.585 0.729 0.18
0.405 0.738 0.36
0.045 0.762 0.72
0.033 0.582 0.732
0.024 0.402 0.741
0.012 0.225 0.75
0.003 0.045 0.762
0 0 0.621
0 0 0.429];
colormap(RGB)
colorbar
caxis([0,max(2107)])
I would like to set the labels following the vecor label,
label = [ 2.7290e+000
4.2512e+000
6.6224e+000
1.0316e+001
1.6070e+001
2.5034e+001
3.8998e+001
6.0750e+001
9.4634e+001
1.4742e+002
2.2965e+002
3.5774e+002
5.5728e+002
8.6812e+002
1.3523e+003
2.1066e+003];
And put the tick and labels exactly on the color divisions.
Any idea about how to do it?

Best Answer

The actual colorbar range will be from 0 to the number of labels.
The actual colorbar ticks are at x.5 for each integer between the limits.
The colorbar tick labels are in the format you specified in the label vector.
% Create and set the colormap
RGB=[0.384 0 0
0.525 0 0
0.717 0 0
0.741 0.168 0
0.765 0.333 0
0.765 0.525 0
0.765 0.717 0
0.585 0.729 0.18
0.405 0.738 0.36
0.045 0.762 0.72
0.033 0.582 0.732
0.024 0.402 0.741
0.012 0.225 0.75
0.003 0.045 0.762
0 0 0.621
0 0 0.429];
colormap(RGB)
cb = colorbar();
% Set color labels (one for each row in RGB)
label = [ 2.7290e+000
4.2512e+000
6.6224e+000
1.0316e+001
1.6070e+001
2.5034e+001
3.8998e+001
6.0750e+001
9.4634e+001
1.4742e+002
2.2965e+002
3.5774e+002
5.5728e+002
8.6812e+002
1.3523e+003
2.1066e+003];
% Scale the colorbar and set the ytick labels.
% Since the numeric labels are nonlinear, we
% must use yticklabel; otherwise we could have
% just set them directly using ytick.
caxis([0,numel(label)])
cb.YTick = 0.5 : 1 : numel(label);
labelChar = strsplit(sprintf('%0.2e ',label));
cb.TickLabels = labelChar(1:end-1);
cb.FontSize = 8;
You may want the set the tick direction to out so the y ticks can be seen better.
cb.TickDirection = 'out'; % (not show in the image below)