
Can someone show me how to put the labels inside the colorbar?
7 views (last 30 days)
Show older comments
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

0 Comments
Accepted Answer
Adam Danz
on 25 Apr 2019
Edited: Adam Danz
on 6 Apr 2021
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.
3 Comments
Andrew Frassetto
on 6 Apr 2021
@Adam Danz - thank you! This helped me with a problem today - so wonderful!
More Answers (0)
See Also
Categories
Find more on Color and Styling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!