How to make 2-line labels on a colorbar?
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 9 Apr. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Colorbar finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!