필터 지우기
필터 지우기

How to make 2-line labels on a colorbar?

조회 수: 21 (최근 30일)
KAE
KAE 2018년 4월 9일
댓글: KAE 2018년 8월 7일
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

채택된 답변

Walter Roberson
Walter Roberson 2018년 4월 9일
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
Bijay Guha
Bijay Guha 2018년 8월 7일
How to create colorbar like the attached image.. Thank You
KAE
KAE 2018년 8월 7일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Colorbar에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by