How do I create a multi-line tick label for a figure using MATLAB 7.10 (R2010a)?
574 次查看(过去 30 天)
显示 更早的评论
I have created a plot and I wish to set XTickLabel and YTickLabel such that it contains multiple lines.
采纳的回答
MathWorks Support Team
2010-7-9
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 个评论
Scott MacKenzie
2021-5-3
编辑:Scott MacKenzie
2021-5-28
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/606270/image.jpeg)
更多回答(3 个)
Adam Danz
2020-6-3
编辑:Adam Danz
2023-3-24
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/309332/image.png)
Note, this solution requires using the default tex interpreter in the tick label interpreter.
ax.TickLabelInterpreter = 'tex';
8 个评论
Adam Danz
2023-4-4
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.
dpb
2023-4-4
It isn't a workaround, of course, but incorporating the 'HorizontalAlignment' named parameter would be the elegant solution...
Keith Rice
2020-5-15
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');
0 个评论
Scott MacKenzie
2021-4-2
编辑:Scott MacKenzie
2021-4-2
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/570479/image.jpeg)
5 个评论
Scott MacKenzie
2021-4-27
编辑:Scott MacKenzie
2021-4-27
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.
Adam Danz
2021-4-28
编辑:Adam Danz
2021-4-28
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/599745/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/599750/image.png)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Labels and Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!