LaTeX in MATLAB multi-line titles
Asked Answered
A

3

6

I need to create a two-line title in a MATLAB plot, using LaTeX in each of the lines.

title({'first line','second line'})

works, but not with LaTeX. In a single line MATLAB title, LaTeX is understood as in the example:

title(['$y=x^2$'],'interpreter','latex')

I have tried many things, but I haven't managed to have MATLAB produced a multi-line title with LaTeX in those lines.

Aaronaaronic answered 6/11, 2015 at 10:30 Comment(0)
I
4

Up to version R2017a, using a cell array, as suggested by other answers, forced left alignment. This seems to have been fixed in R2017b.

You can wrap the title in a LaTeX tabular environment:

figure;
plot((1:5).^2);
title('\begin{tabular}{c} first_line \\ second_line \end{tabular}', ...
      'interpreter', 'latex')

This will let you choose text alignment. Replace {c} with either {r} or {l}, for right and left aligned text, respectively.

Idiolect answered 6/11, 2015 at 10:49 Comment(0)
S
7

If you run

title({'$y=x^2$','$y=x^2$'},'interpreter','latex')

you will get a two-line title with correct LaTeX-ification.

Straight answered 6/11, 2015 at 14:35 Comment(4)
Perhaps you were trying to execute some ill-formed LaTeX formatting? Try posting the actual LaTeX commands that failed if you are still having trouble. Also, post which version of MATLAB you are using.Straight
Yeah, much more cleaner than the other solutions. Nice job.Lisbethlisbon
This accepted answer lets the user choose text alignment (centred alignment in his example), while the answer above does not. Using a cell array will force (the often undesired) left alignment. This is likely a bug.Krantz
Using a cell array uses centered alignment in R2020b.Akim
I
4

Up to version R2017a, using a cell array, as suggested by other answers, forced left alignment. This seems to have been fixed in R2017b.

You can wrap the title in a LaTeX tabular environment:

figure;
plot((1:5).^2);
title('\begin{tabular}{c} first_line \\ second_line \end{tabular}', ...
      'interpreter', 'latex')

This will let you choose text alignment. Replace {c} with either {r} or {l}, for right and left aligned text, respectively.

Idiolect answered 6/11, 2015 at 10:49 Comment(0)
T
1

You can use sprintf to create the string for the title, explicitly with a newline character, '\n'.

title(sprintf('$y=x^3$\n$sin(x)$'), 'interpreter', 'latex');
Twodimensional answered 6/11, 2015 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.