Saving figure to pdf prints # instead of tabs in titles - matlab

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')

Related

Fix extra space in MATLAB's title plot

I'm writting the results for my thesis, this includes the generation of figures for my LaTeX document by using MATLAB code. I do this by making a figure of the data, and then I use the print command to save in an EPS file.
The problem is that the plot in the MATLAB window is correct as you can see here:
But when I compile my document in LaTeX (Lyx), the result is this:
.
As you can see, I have an unexpected big extra space in "iLm" title. The same occurs when I use LaTeX code in the label of different signals.
Searching in the web I tried the following command:
set(groot,'DefaultTextInterpreter','latex');
But just prints "iL_m" like I wrote in the code. How can I make the spacing consistent in the EPS file?
Here's the code I'm using:
clear h n
figure(1)
h(1) = plot(iLmVal.time,iLmVal.data(:,2),'LineWidth',1,'color','k','DisplayName','Modelo');
hold on
h(2) = plot(iLmVal.time,iLmVal.data(:,4),'LineWidth',1,'color','r','DisplayName','Circuito');
legend(h,'Location','southeast'),...
axis([0 0.06 -18 27]),title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times-Roman'),...
set(gca,'Color','white');
set(gca,'XTick',0:0.005:0.06),...
set(gca,'XTickLabel',0:5:60,'FontSize',20,'FontName', 'Times-Roman','XMinorGrid','on'),...
xlabel('Tiempo [ms]','FontSize',20,'FontName', 'Times-Roman'),...
set(gca,'YTick',-18:4:28),...
set(gca,'YTickLabel',-18:4:28,'FontSize',20,'FontName', 'Times-Roman','YMinorGrid','on'),...
ylabel('Corriente [A]','FontSize',20,'FontName', 'Times-Roman'),...
n = gca;
n.YAxis.MinorTick = 'on'; n.YAxis.MinorTickValues = -18:1:28;
n.XAxis.MinorTick = 'on'; n.XAxis.MinorTickValues = 0:0.0025:0.07;
grid on; hold off
I'm using MATLAB R2018a and Lyx 2.3.2-2. Also, by printing in PNG this problem doesn't occur, but the quality and resolution is very poor.
I don't think this is related to LyX, you should see this issue in the exported EPS file. You can fix this using a different font.
As you can see in the appearance of the figure in MATLAB, where the title is shown using a sans-serif font (definitely not 'Times-Roman'), MATLAB does not recognize the 'Times-Roman' font, and uses an alternative for rendering. This alternative font is used to determine the location of the subscript, which is positioned independently of the main text by MATLAB. However, this font name is written to the EPS file. When rendering the EPS file in a different program, the 'Times-Roman' font is recognized and used to render the text. Because this font has different metrics to the one used by MATLAB, the location of subscripts is not correct.
When printing to PNG, MATLAB creates a bitmap, therefore this problem does not occur.
On my computer (macOS), the fooling produce a correct representation on screen:
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times-Roman')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','TimesRoman')
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times New Roman')
The following doesn't:
title("Corriente de magnetización iL_m",'FontSize',20,'FontName','Times Roman')
On different computers, different font names will be available. Use a name that is recognized on your computer. Your best bet is 'Times', which is the PostScript name for this font and should be recognized everywhere.
Alternatively, use the export_fig utility on the File Exchange. This is a great tool for exporting MATLAB figures to EPS. It will not only fix your fonts, but make many other little tweaks that will improve the look of your figures.

Adjusting graphical LaTeX text size in 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.

Exporting figures as vector graphics in .pdf-format using HG2-Update and 'painters' renderer is not working properly

I'm using the still undocumented HG2-Update to create my MATLAB plots, because they just look that much nicer.
(Source: Yair Altman)
Actually, using the current version Release 2013b it works quite nicely and there are not much issues. Except one wants to export the figures as vector graphics (renderer: '-painters'), especially as pdf.
I use the commands:
saveas(gcf,'test.pdf','pdf')
or
print(gcf,'test.pdf','-dpdf')
There are rendering issues, the print does not contain the whole figure and some parts are cropped or non-default fonts are not recognized.
But I'd really like to stay with HG2 and I'd still like to use vector graphics. Is there any solution or workaround?
Exporting vector graphics using the yet not official HG2-Update is quite an issue. The .pdf-export is still totally screwed up.
What is working fine is the .svg-export, apart from that the boundary box is not set properly.
The long workaround would be:
Save the plot with '-dsvg' (print-command) or 'svg' (saveas-command) as vector graphic, open the file in the open source application Inkscape and save again as .pdf with the Export area is drawing checkmark set.
Quite complicated, so I found a way to do it via command-line directly from Matlab (Inkscape still required!):
filename = 'test';
inkscapepath = '"C:\Program Files (x86)\Inkscape\inkscape.exe"';
%// save as .svg
saveas(gcf,filename,'svg')
%// open and save with "export-area-drawing" set via command line
system( [inkscapepath ' ' filename ...
'.svg --export-area-drawing --export-pdf=' filename '.pdf'])
It takes some time, but works without any known issues for now.
Additionally delete the svg-File afterwards:
delete([filename '.svg'])
I had the same problem and used the workaround from thewaywewalk. Now I discovered the MATLAB function "hgexport" works under HG2 (in R2014a).
An issue still was the paper size. I want to use the same size for all graphs with as little white frame as possible. Here you have to set two sizes:
The papersize is set with set(gcf,'PaperSize',[width height]) and the size of your chart is set through export styles. These are set in "Export Setup" or command line:
exp_style=hgexport('readstyle','default');
exp_style.Width = 'width';
exp_style.Height = 'height';
exp_style.Renderer = 'painters';
Now you can export your pdf:
hgexport(gcf,'pdfname',exp_style,'Format','pdf');
PS: In HG2 you may also use Latex for tick labels:
set(gca,'TickLabelInterpreter','latex');

How to set the font settings in .pdf, publish via MATLAB and LATEX

While trying to publish a .pdf file for .m MATLAB code, equations (written in latex) are not properly rendered in appropriate (smooth) font, instead fonts looks scattered.
I did try to fix the problem by decreasing the font-size of the editor but that didn't work.
For example: the MATLAB code is:
%% (a) From above plot there are no signs of convergence of $\rho$
%%
% $x^2+e^{\pi i}$
then the .pdf file is not well written, in which equation's fonts are not smooth enough.
thanks for any suggestions.
I was having the same problem, with equation rendering quality being inadequate.
This is my procedure for fixing this in MATLAB R2013b.
1) In the MATLAB command prompt, enter:
edit publish
This should pop up the editor for you to edit 'publish.m'. Beware, the file may be read only. Under Linux, I use an external editor as superuser to edit it.
2) Go to line 811. You should see this:
temptext = text('Parent',tempaxes,'Position',[.5 .5], ...
'HorizontalAlignment','center','FontSize',22, ...
'Interpreter','latex');
Change the value of 'Fontsize' to something larger; I used 30.
3) Go to line 747. You should see this:
swapTexForImg(dom,equationNode,outputDir,fullFilename,equationText,newSize(2),newSize(1))
Change that to
swapTexForImg(dom,equationNode,outputDir,fullFilename,equationText,newSize(2)/scale,newSize(1)/scale)
where scale is the scale factor of your liking. Might have to play with it a bit until you get it right; I used 2.
4) Save the file. Also keep a backup of the original.
5) In the MATLAB command prompt, enter:
rehash toolboxcache
followed by:
clear functions
6) Run publish again.
This should do the job for the PDF. I haven't tried it for HTML, but it should also work. In case of HTMl, don't forget to delete the images created previously.

How do you use the LaTeX blackboard font in MATLAB?

So, based on my question and solutions here, I would like to actually start using LaTeX, in figures as seen. However, one problem I am running into, is that I cannot seem to display the Expectation operator.
From my research, I know that the expectation operator can be displayed as such normally as such:
/mathbb{E}
However, when I try to use it in MATLAB, nothing prints out.
clear all
figure(1); clf(1);
set(gcf, 'color', 'white'), axis off %# Remove axes and set white background
my_text = '$$ \mathbb{E} $$';
text('units', 'inch', 'position', [-0.5 3.5], 'fontsize', 14, 'color', 'k', ...
'interpreter', 'latex', 'string', my_text);
Now, I know that the \mathbb is some sort of different 'library', but frankly it is quite useful for mathematical formulations. How do I 'include' it in MATLAB? I am lost on this.
You might not have noticed it, but you get an warning message in the command prompt:
Warning: Unable to interpret TeX string
which tells you that MATLAB has trouble parsing your LaTeX expression. More specifically, the blackboard bold math font (indicated by the '\mathbb') is not supported by MATLAB's built-in LaTeX interpreter (it requires the amsmath package).
One way to install this package is described here and here. I'll summarize it for you:
Download the AMS-LaTeX package from here.
Modify the m-file tex.m, which is located in the MATLAB root\toolbox\matlab\graphics folder (backup the file before modifying it):
2.1. In the localDecorateInputString function, modify standardhead to include the new packages (marked in bold):
standardhead = [' \nofiles \documentclass{mwarticle} \usepackage{amsfonts, amsbsy, amssymb} \begin{document}']
2.2. In the `localGetTeXPath` function, add the paths of where the AMS package files are located (marked in bold), for instance:
texpath{1} = blah blah blah...
texpath{end+1} = blah blah blah...
texpath{end+1} = 'C:\amslatex';
Copy all .sty files of the AMS package to the MATLAB root\sys\tex folder.
Restart MATLAB.
You should now have the necessary LaTeX font packages installed. I would've gladly checked it out myself if time allowed, it seems promising.
Another way of going about this is to export the figure to an eps file and using the psfrag to retroactively replace all of your standard E's with their Blackboard Bold equivalents.
\psfrag{E}{\mathbb{E}}