Adjusting graphical LaTeX text size in Matlab - matlab

I am trying this example:
http://www.mathworks.com/help/symbolic/latex.html
Let's say I wanted to resize those labels. How? I can't figure out any LaTeX code, and 'fontsize' does not do the trick.

This hits a sore spot when it comes to Matlab's support for (or use of) Latex. The normal font-size commands from Latex aren't available. (In Latex normally you'd just say \Large{Text ... $x$} or even \normalsize ....)
To do this in a Matlab plot you can add fontsize spec at the end
title(['For $x$ and ...'], 'Interpreter', 'latex', 'fontsize', 14)
For more discussion and how to change font type as well see this post. Note that there are not so many fonts readily available in Matlab. To preserve sanity I'd keep this kind of tweaking to the minimum.
There is another method that will work anywhere in Matlab where you can use Latex -- in any text, in the middle of a string, etc: You can drop to Latex's lower level font specification.
title(['\fontsize{15}{0}\selectfont For $x$ and ...'], 'Interpreter', 'latex')
The first command \fontsize{}{} specifies the font, the second one \selectfont actually changes it for the rest of the text. When you want to switch to a different font, even mid-string, you again issue \fontsize{12}{0}\selectfont and you have that font size after that point. The only thing you need to change is the size (I used 15 and 12 as examples), the rest is boilerplate (for this purpose).
See what these things mean and more discussion in this post. For far more detail on fonts in Matlab see this article. For how to change fonts across the whole document see this post.
There are yet other ways but it gets progressively trickier and this should be enough. Probably the best advice is to set it once for the whole document. That also makes sense typesetting-wise.
Note. The font command of the second example must be given outside of math mode. Latex has two major modes, text and math. To make it go to 'math mode', where it processes everything as it were math symbols, you put a $, or $$. (There are yet many other ways, but in Matlab's strings this is all you'll ever use.) When you want it to go back to typesetting text normally, you end math mode with another $, or $$. All math is in between $...$, everything else is normal text.
This is some text, now typeset some math: $y = x^2$ ... back to text.
The font commands do not work in math mode but need be given outside the $...$. They will apply to any following math as well. In a plot command we'd say
ylabel(['\fontsize{16}{0}\selectfont $\dot{x}$'], 'interpreter','latex');

Here is the line that worked:
ylabel('$x_e, x_c$', 'interpreter','latex', 'fontsize', 32);
Obviously, between the dollar signs can be whatever appropriate LaTeX expression desired.

Related

Saving figure to pdf prints # instead of tabs in titles

if I create a plot with some tabs in the titles and try saving that to a local pdf file (via print function), I get some hashtags instead of tabs in the pdf. This does not occur in the visible figure.
For example, I plotted the residuals of an approximant to the runge function on a grid:
plot(g, f(g) - runge(g));
title(sprintf('residuals,\t max_x(s-f) = %.3f', max(f(g)-runge(g))));
Then after some axes manipulation (grid, boxes, etc..) I execute
h = gcf;
set(h,'Units','Inches');
pos = get(h,'Position');
set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])
print(h,'data/runge_example.pdf','-dpdf','-r200')
close(h)
Is somebody aware of that behaviour or better able to found that as already solved than I am?
EDIT: Same behaviour with saveas and saving to eps. This does not happen with \n
EDIT2: I'm using Matlab Version R2017b (9.3.0.7...)
So, after a long discussion we figured out that we have no idea of how to use tabs in matlab titles in combination with latex mode.
To clarify: use math environments and escape tex directives, otherwise it will throw an error.
so
sprintf('residuals,\t $max_x(\\vert s-f\\vert) = %.3f$', max(f(g)-runge(g))));
will give you a nice string:
residuals, $max_x(\vert s-f\vert) = 0.264$
The problem is, that it really is a tab. And the matlab latex interpreter (don't know which one that uses, the system or an own) crashes on that. I copy-pasted that to a tex document and pdflatex ran fine on it (but not showing that much space unfortunately).
So, I came up with the following fix:
use the latex directive \quad or \qquad:
title(sprintf('residuals,\\quad $max_x(\\vert s-f\\vert) = %.3f$', max(abs(f(g)-runge(g)))));
This will give you more space than a normal space.
EDIT: For this to work you need the interpreter of matlab to be set to "latex" instead of the default "tex". Do this by changing the title to
title(title_string, 'Interpreter', 'latex')
or by setting (globally for that script)
set(groot, 'defaultTextInterpreter', 'latex')

MatLab Eps Print Webdings interpreter

So recently I decided to not use the standard markers that Matlab provides and use my own via: a set of fonts including Webdings or WingDings. I make a standard scatter plot, and plot the text (in wingdings), using the text command, over the locations of the markers.
When I save these plots as png files, they print perfectly. They also appear perfectly on my screen after plotting.
However when I save these plots as eps files, the webdings are turning into their original letters 'l' or 'w'. It also looks like it's plotting them in a Courier font, but my default is Helvetica.
I've read through this previous post, but my question differs in that he is looking to use Latex as the interpreter and to include fonts, whereas I don't want to use Latex as the interpreter. However, it seems like my default interpreter (not sure what that is), isn't doing the job when converting to EPS.
Example:
imageR='w'
text(xf2,yf2,imageR,'fontName',font,'FontSize',fontR,'HorizontalAl','left','color','w')
I figured it out....took me way too long.
Ghostscript / Postscript only export with a few fonts when you are exporting eps files.
This link was incredibly helpful.
I just switched from wingdings/webdings to ZapfDinbats...Practically the same thing...

Latex fonts in matlab

Is it possible to convert the font of a matlab plot to be the same of latex fonts. For example I can modify the font of a plot by:
x = -pi:.1:pi;
y = sin(x);
plot(x,y)
set(gca,'FontName','Helvetica');
Is it possible to do the same but for latex fonts (I say latex fonts as I am not sure of the actual name of the font latex uses as its basic font).
For any text object you just need to set the 'Interpreter' property to 'latex'. So, for example you could do
xlabel('$$\int_0^x\!\int_y dF(u,v)$$','Interpreter','latex');
For tick labels it is more difficult, though there may be files available to make it easier (example).
I'd recommend setting the default interpreter to LaTex at the beginning of your script/function:
set(0,'defaulttextinterpreter','latex')
You can also download a version of Computer Modern (The LaTeX Font Family) and install it to your machine. Techniques may vary if you're running windows or mac, for Mac you'll need to download the OTF version and add it into the FontBook (Cmd-Space: FontBook)
Next, restart Matlab
Finally, you can use the LaTeX Font in Matlab:
set(0,'DefaultTextFontname', 'CMU Serif')
set(0,'DefaultAxesFontName', 'CMU Serif')
This is a nice work-around for having constant fonts in your tick-labels, although it has some trouble exporting in some formats.
You can define the font within the latex strings. For instance, to change between serif font (Roman) and sans serif font (Helvetica, I guess):
text(0.5, 0.8, '\textsf{sans serif}','interpreter','latex')
text(0.5, 0.7, '\textrm{roman}','interpreter','latex')
text(0.5, 0.6, '$$\mathsf{math\,\,mode\,\,sans\,\,serif}$$','interpreter','latex')
text(0.5, 0.5, '$$\mathrm{math\,\,mode\,\,roman}$$','interpreter','latex')
For true matching of fonts (including LaTeX-style kerning, ligatures etc.), the text in the Matlab figure needs to be typeset with LaTeX. The laprint script, which uses psfrag, is a straightforward way of doing this.
If you export to .eps you can just edit the figure afterwards with a simple text editor and exchange the fonts in there. It is a bit fiddly but does the trick. You can also change the kerning of each character individually (because its position is hard-coded in there).
It is also possible to change each character's font individually (I sometimes do this, if a need a symbol from Latex (i.e. Computer Modern), but want the rest of the label in Helvetica again)
Disclaimer: I'm not the expert.
However, linux's command fc-list lists all fonts on your system, I think they are all supported by Matlab.
In ubuntu (and possibly other distro's) the latex font is called Latin Modern, or lm for short. You can find them all via:
# fc-list | grep lmroman
/usr/share/texmf/fonts/opentype/public/lm/lmroman10-bold.otf: Latin Modern Roman,LM Roman 10:style=10 Bold,Bold
/usr/share/texmf/fonts/opentype/public/lm/lmroman7-italic.otf: Latin Modern Roman,LM Roman 7:style=7 Italic,Italic
... etc etc...
Between the colon and the first comma it says Latin Modern Roman, which is the name of the Roman font of Latin Modern, there is also:
Latin Modern Sans
Latin Modern Roman Caps
Latin Modern Mono
etc etc
I think these fonts are used when you call \textrm (roman), \textsf (serif), etc etc, in latex in mathmode. Of course, you can find them all via the fc-list command.
To get the latex font in your plots, simply execute:
plot(rand(10), 'o');
xlabel('index', 'FontName', 'Latin Modern Roman', 'FontSize', 25);
ylabel('value', 'FontName', 'Latin Modern Roman', 'FontSize', 25);
set(gca, 'FontName', 'Latin Modern Roman', 'FontSize', 25);
And the result is a nice:
PS: Latin Modern is not exactly the same as Computer Modern, but they look alike and I wouldn't know how much they really differ.
Regarding Matlab's Interpreter option, to the best of my knowledge it does not apply to all textual elements of a plot, like the axe labels:
>> plot(rand(10), '.'); set(gca, 'Interpreter', 'latex');
Error using hg.axes/set
The name 'Interpreter' is not an accessible property for an instance of class 'axes'.
Unfortunately, matlab's print function is flawed, as it is not able to embed fonts into eps or pdf files. For this reason generated files may have substituted fonts, even on the same system. To tackle this, this library allows you to embed the fonts: http://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig
Make sure to set the background of your figure to white, before exporting it and note that the library may take a lot of memory, as it calls ghostscript.
Moreover, changing the interpreter seems like overkill if you wish to change the font.
From Matlab version 2014, the below command can be used.
set(gca,'TickLabelInterpreter','latex')
If you aim at exporting MATLAB figures into LaTeX and want a consistent look-and-feel (including the fonts), you should use matlab2tikz (a project I once started).

MATLAB: latex interpreter font spacing

The font spacing in TeX-typeset equations in MATLAB defaults to being highly compressed. Is there a way to increase the amount of spacing, so that, for example, the numerator and denominator of a fraction do not make contact with the line separating the two?
plot(1:10,rand(1,10));
set(gca,'FontSize',18);
legend('$\frac{xy}{\exp\left(\frac{x}{y}\right)}$');
set(legend(),'interpreter','latex');
I think the easiest way is to use some LaTeX trickery.
Long story short, in LaTeX $ ... $ is used for inline math, but for display math, you should either use \[ ... \] or the legacy way of doing the same $$ ... $$. For LaTeX documents, don't use the latter, but for MATLAB it should be enough.
The difference between inline math and display math, is like the difference between using backticks (``) and indentation in StackOverflow. The first will show your code in-between text, the latter in-between paragraphs. With math, only display mode math will have decent lay-out for larger formulas.
So the following code should fix your problem:
plot(1:10,rand(1,10));
set(gca,'FontSize',18);
legend('$$\frac{xy}{\exp\left(\frac{x}{y}\right)}$$');
set(legend(),'interpreter','latex');
If you want even more, you might want to consult the Not So Short Introduction To LaTeX2e which gets you started with a lot of the tricks of the LaTeX trade.
edit:
What I tend to use as a trick to improve spacing in formulae is using phantoms (\phantom, \vphantom, \hphantom), but \vspace or \vskip might be a little cleaner to use.
Looking through the list of properties for the legend, there doesn't seem to be any way of specifying a line spacing that is consistent with automatic positioning. You can fudge the line spacing by enlarging the box, however, by changing the final entry (height) in the OuterPosition property. It seems the placement of the box is based on its bottom-left corner, so if your legend box is in a North position then you will also need to reduce the second entry (y-position) by an equal amount.
In this example I increase the height of a North-positioned legend box by 25% (which I have found that gives nice results), which increases the line spacing.
h = legend(s1,s2,s3, 'location', 'northeast');
set(h, 'fontsize', 16, 'interpreter', 'latex')
outerposition = get(h, 'OuterPosition');
delta_h = 0.25*outerposition(4);
outerposition(2) = outerposition(2) - delta_h;
outerposition(4) = outerposition(4) + delta_h;
set(h, 'OuterPosition', outerposition)
You have to be wary about resizing the figure after running this code fragment, since changing the OuterPosition property clears the automatic placement of the box with respect to the plot axes. If you resize the figure the legend box will go walkabouts.

Matlab: Adding symbols to figure

Below is the user interface I have created to simulate LDPC coding and decoding
The code sequence is decoded iteratively by passing values between the left and right nodes through the connections.
The first thing it would be good to add in order to improve visualization is to add arrows to the connections in the direction of passing values. The alternative is to draw a bigger arrow at the top of the connection showing the direction.
Another thing I would like to do is displaying the current mathematical operation below the connection (in this example c * H'). What I don't know how to do is displaying special characters and mathematical symbols and other kinds of text such as subscript and superscript in the figure (for example sum sign and subscript "T" instead of sign ="'" to indicate transposed matrix).
I would be very thankful if anyone could point to any useful resources for the questions above or show the solution.
Thank you.
To add arrows, you can either use the built-in QUIVER, or, for more options, ARROW from the file exchange. Both of these have to be plotted into axes, so if you want a big arrow on the top, you have to create an additional set of axes above the main axes.
As far as I know, you cannot use TeX or LaTeX symbols in text uicontrols. However, you can use them in axes labels. Thus, I suggest that you add an XLabel to the axes, for example
xlabel('\sigma c*H_T')
or (note the $-signs required for LaTeX)
xlabel('$\sum c*H_T$','interpreter','latex')
EDIT
I hadn't mentioned the use of text (as suggested by #gnovice and #YYC) because I thought it wasn't possible to place text outside of the axes. It turns out that I was wrong. text(0.5,-0.2,'\Sigma etc.') should work fine as well. I guess the only advantage of using 'xlabel' would be that you can easily add and position the axes label during GUI creation.
In regards to the 1st question, annotation (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/annotation.html) might be an alternative solution.
In regards to the 2nd question, try text property in Matlab Help.
Search "Character Sequence" for the special characters; search "Specifying Subscript and Superscript Characters" for the subscript and superscript.
For drawing the arrow, I would go Jonas' suggestion arrow.m by Erik Johnson on the MathWorks File Exchange. It's the easiest way I've found to create arrows in figures.
For creating text with symbols, you can use the function TEXT. It lets you place text at a given point in an axes, and you can use the 'tex' (default) or 'latex' options for the 'Interpreter' property to get access to different symbols. For example, this places the text you want at the point (0,0) using 'latex' as the interpreter:
hText = text(0,0,'$\sum c*H_T$','Interpreter','latex');
The variable hText is a handle to the text object created, which you can then use with the SET command to change the properties of the object (string, position, etc.).