Effacer les filtres
Effacer les filtres

How to make 2-line labels on a colorbar?

21 vues (au cours des 30 derniers jours)
KAE
KAE le 9 Avr 2018
Commenté : KAE le 7 Août 2018
I would like to have my colorbar text labels to each have two lines. For example, the -6 tick in the example below would be labeled '-6' (first line) and 'a' (second line). The -4 tick would be labeled '-4' (first line) and 'b' (second line). Is this possible? If so how?
I did try putting the second line of text on a separate axis (attempt #4 below), but the axis labels don't line up with the colorbar labels if the figure is resized. If there is a fix to keep the axis labels aligned with the colorbar ticks, it would be a fine workaround.
figure;
peaks % Make an example color plot
h = colorbar('southoutside'); % Get the handle to the colorbar
h.Ticks = -6:2:8; % Set tick values
% #1 Set 1-line tick labels. This works but we want 2-line labels.
h.TickLabels = {'-6', '-4', '-2', '0', '2', '4', '6', '8'};
% #2 Try making 2-line labels with cell arrays, which fails
h.TickLabels = {{'-6','a'}, {'-4','b'}, {'-2','c'}, {'0','d'}, ...
{'2','e'}, {'4','f'}, {'6','g'}, {'8','h'}};
Error setting property 'TickLabels' of class 'ColorBar':
Cell array can contain only non-empty character vectors, string vectors, or numbers.
% #3 Try making 2-line labels with character array containing newline character
h.TickLabels = {sprintf('-6\na'), sprintf('-4\nb'), sprintf('-2\nc'), ...
sprintf('0\nc'), sprintf('2\nd'), sprintf('4\ne'), sprintf('6\nf'), ...
sprintf('8\ng')};
% No error returned, but 2-line labels are unwrapped into 1 line so labels are wrong
% #4 Try putting the 2nd line of label text on a separate 'fake' axis
colorTickLabels2 = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
hTop = axes('pos', h.Position); % Make a 'fake' axis that overlays the colorbar
set(hTop, 'xgrid', 'off', 'ygrid', 'off', 'xtick', h.Ticks, 'ytick', [], ...
'xaxisloc', 'top', 'xlim', h.Limits, 'xticklabels', colorTickLabels2);
% This works great until you resize the figure
% But make it full screen and the 'fake' axis no longer lines up
% with the colorbar

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Avr 2018
Example: '-6 \newline a', '-4\newline{b}'
That is, you do not need a space before, but after you need some element to mark the end of the term, which could be a space.
  3 commentaires
Bijay Guha
Bijay Guha le 7 Août 2018
How to create colorbar like the attached image.. Thank You
KAE
KAE le 7 Août 2018
Hi Bijay, Could you please start a new question since you are asking something different than the original question? You will be more likely to get an answer that way.

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by