How do I create a multi-line tick label for a figure using MATLAB 7.10 (R2010a)?
574 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 9 Jul. 2010
Kommentiert: dpb
am 4 Apr. 2023
I have created a plot and I wish to set XTickLabel and YTickLabel such that it contains multiple lines.
Akzeptierte Antwort
MathWorks Support Team
am 9 Jul. 2010
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 Kommentar
Scott MacKenzie
am 3 Mai 2021
Bearbeitet: Scott MacKenzie
am 28 Mai 2021
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)
Weitere Antworten (3)
Adam Danz
am 3 Jun. 2020
Bearbeitet: Adam Danz
am 24 Mär. 2023
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 Kommentare
Adam Danz
am 4 Apr. 2023
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
am 4 Apr. 2023
It isn't a workaround, of course, but incorporating the 'HorizontalAlignment' named parameter would be the elegant solution...
Keith Rice
am 15 Mai 2020
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 Kommentare
Scott MacKenzie
am 2 Apr. 2021
Bearbeitet: Scott MacKenzie
am 2 Apr. 2021
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 Kommentare
Scott MacKenzie
am 27 Apr. 2021
Bearbeitet: Scott MacKenzie
am 27 Apr. 2021
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
am 28 Apr. 2021
Bearbeitet: Adam Danz
am 28 Apr. 2021
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)
Siehe auch
Kategorien
Mehr zu Labels and Annotations 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!