MATLAB: Can someone show me how to put the labels inside the colorbar

MATLABmatlab colorbar

Dear all,
I get a problem to put the labels of each colors inside the colorbar(the left one), as what has done in the published paper figure(the right one).
Can somebody help me? Many thanks to you.
Shan Yin
untitled.png TIM截图20190425230139.png

Best Answer

Since you can't add text objects to the colobar, you can add an invisible axis on top of the colorbar and place the ticks there.
% Create fake data to work with
surf(peaks(15))
colormap(lines(15))
cbh = colorbar;
cbh.Ticks = -6:1:8;
caxis([-6,9]);
% Make sure all ticks are present prior to moving on.
ticks = strsplit(num2str(cbh.Ticks));
ax = axes('Position', cbh.Position);
edges = linspace(0,1,numel(ticks)+1);
centers = edges(2:end)-((edges(2)-edges(1))/2);
text(ones(size(centers))*0.5, centers, ticks, 'FontSize', cbh.FontSize,...
'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Middle');
ax.Visible = 'off'; %turn off new axes
cbh.Ticks = []; %turn off original ticks
Note: This approach is OK with categorical data where each tick is associated with one discrete color. This approach could result in erroneous colorbar labels if the data are on a continuous scale. For continuous data, leave the cbh.Ticks (last line) visible to ensure that they match with the kludged ticks along the y axis of the colobar.