How do I create a multi-line tick label for a figure using MATLAB 7.10 (R2010a)?

I have created a plot and I wish to set XTickLabel and YTickLabel such that it contains multiple lines.

 Accepted Answer

There is no function that will allow you to create a tick label consisting of multiple lines.
As a workaround, you can replace the tick labels with text objects which can contain multiple lines of text. For example:
%%Create figure and remove ticklabels
plot(1:10);
set(gca,'yticklabel',[], 'xticklabel', []) %Remove tick labels
%%Get tick positions
yTicks = get(gca,'ytick');
xTicks = get(gca, 'xtick');
%%Reset the YTicklabels onto multiple lines, 2nd line being twice of first
minX = min(xTicks);
% You will have to adjust the offset based on the size of figure
VerticalOffset = 0.1;
HorizontalOffset = 0.6;
for yy = 1:length(yTicks)
% Create a text box at every Tick label position
% String is specified as LaTeX string and other appropriate properties are set
text(minX - HorizontalOffset, yTicks(yy) - VerticalOffset, ['$$\begin{array}{c}',num2str( yTicks(yy)),'\\',num2str( 2*yTicks(yy)),'\end{array}$$'], 'Interpreter', 'latex')
% {c} specifies that the elements of the different lines will be center
% aligned. It may be replaced by {l} or {r} for left or right alignment
end
%%Reset the XTicklabels onto multiple lines, 2nd line being twice of first
minY = min(yTicks);
% You will have to adjust the offset based on the size of figure
VerticalOffset = 0.6;
HorizontalOffset = 0.2;
for xx = 1:length(xTicks)
% Create a text box at every Tick label position
% String is specified as LaTeX string and other appropriate properties are set
text(xTicks(xx) - HorizontalOffset, minY - VerticalOffset, ['$$\begin{array}{c}',num2str( xTicks(xx)),'\\',num2str( 2*xTicks(xx)),'\end{array}$$'], 'Interpreter', 'latex')
% {c} specifies that the elements of the different lines will be center
% aligned. It may be replaced by {l} or {r} for left or right alignment
end

1 Comment

I tried this. While I appreciate the advantage of having "real" tick labels rather than judiciously positioned multi-lined text objects, the solution above has at least two problems. First, the default latex font is a serfif font. This is fine for text documents, but is a poor choice for charts. Even worse is mixing the fonts because other labels added to the chart will use MATLAB's default font for graphics, which is a sans serif font.
Second, the position of axis labels is not recalculated to account for the multi-line tick labels. As a result, axis labels are superimposed on the tick labels. Just to illustrate, if I add
legend({'A Blue Line'}, 'location', 'south'); % different font
xlabel('X Axis Label'); % wrong position
ylabel('Y Axis Label'); % wrong position
to the example script above, here is the result:

Sign in to comment.

More Answers (3)

A more modern approach to setting multi-row tick labels.
Recent releases of Matlab have made it easier to set multiple rows of tick labels. Here's a demo.
% Define each row of labels.
row1 = {'White' 'Green' 'Red' 'White' 'Green' 'Red'};
row2 = {'East' 'East' 'East' 'West' 'West' 'West'};
row3 = 10.5:15.5;
% Combine the rows of labels into a cell array; convert non-strings to strings/character vectors.
% labelArray is an nxm cell array with n-rows of m-tick-lables.
labelArray = [row1; row2; compose('%.1f',row3)];
% To use right or center justification,
% labelArray = strjust(pad(labelArray),'center'); % 'left'(default)|'right'|'center
% Combine the rows of labels into individual tick labels
% Change the compose() format according to your label classes.
% Place the \\newline command between rows of labels.
% This plot has 3 rows of labels so there are 2 \\newline commands.
tickLabels = strtrim(sprintf('%s\\newline%s\\newline%s\n', labelArray{:}));
% tickLabels = strsplit(tickLabels); % Optional
% Assign ticks and labels
ax = gca();
ax.XTick = 1:6;
ax.XLim = [0,7];
ax.XTickLabel = tickLabels;
% ax.TickLabelInterpreter = 'tex'; % needed for some plots like boxplot.
xlabel('Easy as pie')
The same can be applied to the y-axis labels.
Note, this solution requires using the default tex interpreter in the tick label interpreter.
ax.TickLabelInterpreter = 'tex';

9 Comments

That's not quit correct. This method does work for YTickLabel but of course the labels will overlap if your axis hight is small.
There are two ways to fix that.
  1. Increase the height of your axes.
  2. Decrease font size of the YTickLabels.
@Stefan Dukic , thanks for mentioning that. For boxplots, you just need to set,
ax.TickLabelInterpreter = 'tex';
I've updated my answer to include that recommendation.
Thanks, and nice suggestion, Jose.
If your labels are long but have different lengths between the rows, you may want to right-justify the text. I just added a line to my answer (commented-out) to show how to do that.
Hi James Tooby, please ask a new question (new question link) so this comment section doesn't turn into its own Q&A forum.
You can leave a new comment here with the link to your question if you'd like me to take a look at it.
From your description above, I don't understand "row1 has 4 entries and row2 would have 8".
@Qian Chu , see these lines in my answer:
% To use right or center justification,
% labelArray = strjust(pad(labelArray),'center'); % 'left'(default)|'right'|'center
Centering text is trick
  1. If a word has an odd number of characters it will be centered. If it has an even number of characters it cannot be exactly centered and will be shifted 1/2 character to the left.
  2. Unless you're using a fixed width font, characters have different widths which will also affect the centering. Look at how the right edge of the labels align differently between two different fonts (below). Set the axis font to a fixed width font for better centering: set(gca,'FontName','Consolas') -or- 'FixedWidth'
@Adam Danz, re your additional edit from Mar 24, '23, thanks. This is getting closer to a workable solution to MATLAB's long-standing "multi-line tick label" problem. The main deal-breaker in your solution, in my view, is that the labels under each tick are left justified, rather than centered.
The result looks OK in your example because the labels on each line are similar in size. But, in other situations, the effect is more apparent:
The preferred arrangement in most situations is this:
Do you know of a simple fix? Not changing the font family is important, of course.
Thanks @Scott MacKenzie. There's a line in my original answer that users strjust to center-justify the rows of labels for each tick label. However, when you assign the tick labels, leading whitespace is eliminated so the horitzontal justification of the first rows of ticks gets messed up and I haven't been able to think of a workaround for that yet.
It isn't a workaround, of course, but incorporating the 'HorizontalAlignment' named parameter would be the elegant solution...
It would be nice if the tick label rendering respected the newline character, instead of relying on the tex interpreter, because sometimes the tex interpreter isn't wanted.
Experimenting with this idea showed a peculiar behavior.
Create a figure
figure
plot(rand(3));
Copy the figure for comparison
hax = copyobj(gca,figure);
Try to change one of the XTickLabels to multiple lines
xtl = hax.XTickLabels
xtl = 5x1 cell array
{'1' } {'1.5'} {'2' } {'2.5'} {'3' }
xtl{2} = char("Line1" + newline + "Line2")
xtl = 5x1 cell array
{'1' } {'Line1...'} {'2' } {'2.5' } {'3' }
xtl{2}
ans =
'Line1 Line2'
hax.XTickLabels = xtl;
So it didn't have the hoped-for behavior, but actually made things worse. Why would the second line of the second requested label become the third label and shift the rest?

Sign in to comment.

10 years later, I found another way to do this based on this feed back. So, first of all, thank you for the original answer here. Latex will also let you do this for tick labels now (not sure if this is new).
This is for the XTicks only but will also work for YTicks
x = 1:5;
y = rand(1,5);
plot(x,y)
for iXTick = 1:length(x)
XTickString{iXTick} = ['$$\begin{array}{c}' ...
'LINE1' '\\'...
'LINE2' '\\'...
'\end{array}$$'];
end
set(gca,'xtick',x,'XTickLabel',XTickString,'TickLabelInterpreter','latex');
I played with the solutions above, but decided to take a DIY approach:
x = 1:4;
y = rand(1,4);
plot(x,y);
ax = gca;
ax.XTick = [1 2 3 4];
ax.XTickLabel = '';
myLabels = { '1', '2', '3', '4';
'Line2a', 'Line2b', 'Line2c', 'Line2d';
'Line-THREE', 'Line-THREE', 'Line-THREE', 'Line-THREE' };
for i = 1:length(myLabels)
text(i, ax.YLim(1), sprintf('%s\n%s\n%s', myLabels{:,i}), ...
'horizontalalignment', 'center', 'verticalalignment', 'top');
end
ax.XLabel.String = sprintf('\n\n\n%s', 'X-Axis Label');
The default x-axis tick labels are removed, then new labels are added using the text function in combination with sprintf and the YLim property. Horizontal and vertical alignments need to be set, as well. This approach gets the proper alignment for the labels and avoids using the latex interpreter. The last line adds an x-axis label using sprintf. The newlines at the beginning push the label down, making room for the two extra lines in the tick labels.

5 Comments

Thanks for sharing, Ian Scott MacKenzie. Using text to assign tick labels produces desireable results for the current state of the axes but several minor but common changes will make this approach inadequate. Since the text object positions are in data units, panning, zooming, or changes to axis limits will mess up the text positions relative to the axes. For this reason, it's recommended to directly change the ticklabels using another method listed here.
Yes, indeed. Thanks for pointing this out. I focus almost entirely on creating figures that are static. When the desired look is achieved, the figure is saved as an image file and used in a research report. For interactive figures, what I describe just won't cut it, for the reasons you note. Thanks again.
Good point, Ethan. Did you also try the latex method explained in the accepeted answer by the MathWorks support team?
Hey, thanks for this. As long as you're just looking to create a static image -- for example a bar chart, line graph, or box plot -- to use in a research report, the approach I described works just fine. And you point out another benefit when exporting as vector graphics. Thanks again.
Hmmm in r2021a I have no problem exporting a demo figure produced in the Mathworks Support Team answer and the demo figure produced in my answer. A screenshot of the svg images from both answers are below and they appear the same as the original figure when imported into a word doc or HTML (svg files attached). SVG files were exported by using the figure's File menu.

Sign in to comment.

Products

Release

R2010a

Community Treasure Hunt

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

Start Hunting!