MATLAB Answers

1

How do I place a two-lined title, x-label, y-label, or z-label on my plot?

I would like to create a multi-lined title, x-label, y-label or z-label. I would like to know if there are any functions in MATLAB that allow me to create a title that uses multiple lines.

2 Answers

Answer by MathWorks Support Team on 12 Jun 2017
Edited by MathWorks Support Team on 12 Jun 2017
 Accepted Answer

You can create multi-line text using a cell array. For example, this code creates a title and an axis label with two lines.
plot(1:10)
title({'First line';'Second line'})
xlabel({'First line';'Second line'})
For more information about creating multiline text, see

  3 Comments

Hi,
This answer was perfect for multi-line title but it did not answer the part of the question about multi-lined x-labelling (or y-label or z-label). In my case, I would like to have a multi-lined label under a bar graph to give additionnal information on the figure.
Is it possible?
Here is an example of code :
decision = [0.5451 0.0335 0.0467 0.3747; 0.8781 0.0135 0.0321 0.0763; 0.9646 0.0054 0.0179 0.0120];
x_labels{1} = sprintf('0 : Acc : 92.0%%\n Spe : 88.9%%\n Sen : 94.2%%');
x_labels{2} = sprintf('1 : Acc : 95.4%%\n Spe : 70.4%%\n Sen : 98.5%%');
x_labels{3} = sprintf('2 : Acc : 97.7%%\n Spe : 40.1%%\n Sen : 99.4%%');
figure;
bar(decisions,'stacked');
set(gca,'XTickLabel', x_labels);
if I try to use the cell format for multi line :
x_labels{1} = {'0 : Acc : 92.0%';' Spe : 88.9%';' Sen : 94.2%'};
x_labels{2} = {'1 : Acc : 95.4%';' Spe : 70.4%';' Sen : 98.5%'};
x_labels{3} = {'2 : Acc : 97.7%';' Spe : 40.1%';' Sen : 99.4%'};
I get the following error :
Error using matlab.graphics.axis.Axes/set While setting the 'XTickLabel' property of Axes: Cell arrays input to String property may only contain character and numeric matrices.
I am using Matlab R2014b :)
After some research, this does the trick : (first download this function : http://www.mathworks.com/matlabcentral/fileexchange/15986-format-tick-labels) then :
x_labels{1} = sprintf('0 : Acc : 92.0%%\n Spe : 88.9%%\n Sen : 94.2%%');
x_labels{2} = sprintf('1 : Acc : 95.4%%\n Spe : 70.4%%\n Sen : 98.5%%');
x_labels{3} = sprintf('2 : Acc : 97.7%%\n Spe : 40.1%%\n Sen : 99.4%%');
set(gca,'XTickLabel', {'','',''});
[hx,hy] = format_ticks(gca,x_labels);
However, I believe there might be some more conventional way of achieving this.
use cell brackets and a semi-colon between each quotation syntax: https://www.mathworks.com/matlabcentral/answers/321502-how-to-add-newline-to-x-label-of-a-plot

Sign in to comment.


Answer by Karan Gill
on 31 Oct 2016

Replace spaces with "\newline".
labels = {'line1 line2','line1 line2','line1 line2'};
labels = cellfun(@(x) strrep(x,' ','\newline'), labels,'UniformOutput',false);
a = gca;
a.XTickLabel = labels;
Karan | Symbolic Math documentation

  1 Comment

Sign in to comment.