File Exchange

image thumbnail

Plot2LaTeX

version 1.2.0.0 (9.79 KB) by Jan de Jong
Exports a figure as a pdf file in vector format for inclusion into LaTeX.

34 Downloads

Updated 20 Apr 2016

View License

PLOT2LATEX saves a Matlab figure as a pdf file in vector format for inclusion into LaTeX. Requires free and open-source vector graphics editor Inkscape. It invokes Inkscape to save the text, labels, legends, titles, etc. to be incorporated into LaTeX. This allows a true LaTeX font and scripts.
Use of the 'PDFLatex' output profile does not directly support psfrag (and therefore laprint or matlabfrag). Plot2LaTex uses the features of Inkscape to export vector image to pdf with supporting pdf_tex file for text placement. Plot2LaTeX supports transparency.
Plot2LaTeX requires Matlab version 2014b or higher.
Plot2Latex requires Inkscape.

Comments and Ratings (64)

Jan de Jong

Dear Philip,
Thank you for your question. I think you can find my email adress on my profile page. Could you send your figure there?
Regards,
Jan

addition:
in a second run the errormsg is:
Unrecognized property 'TickLabelInterpreter' for class 'matlab.ui.controls.AxesToolbar'.

Error in Plot2LaTeX2>ChangeInterpreter (line 464)
Obj(i).TickLabelInterpreter = Interpreter;

Error in Plot2LaTeX2 (line 156)
ChangeInterpreter(h,'Latex')

Hi Jan de Jong,
I have the some problem as Jo.
I am using Linux and the 2019a Matlab.

The first thing i had to change is a change from a backslash to a normals slash in the path of the result. (Line 359).
The second issue is that the status bar stays visible even if the skript is ended.
Now I get an output from inkscape.
But as Jp only with the X000-XNNN Labels.
Before running that command: plot2latex(h, output) everthing looks fine, butafter running that command, the figure in matlab also has the wrong labels.
If i start plot2latex again from commandlinei get:

Unrecognized method, property, or field 'XTickLabel' for class 'matlab.ui.controls.AxesToolbar'.

Error in Plot2LaTeX (line 227)
n_Str = length(AxeObj(i).XTickLabel);

If you send me your mail adress i would send to the figure.

Jan de Jong

Dear Jo,
Too bad it is not working for you. I cannot help you with Linux itself as I am not a user. But to me it seems that Matlab and Inkscape are communicating since the proper files are produced. So I expect that the problem lies somewhere else. Could it be that the figure is large such that matlab automatically switches to bitmap format? Could you send me the figure (.fig) you are testing? Hopefully can figure this out.

jo

Hi Jan,
Thanks for the function.
Sadly, for me the replacement with the original text does not work at all.
All produced formats (svg, pdf) show X000 and I can't find any text in the pdf_tex either. I am using 2017a on linux and also tried the following: https://gist.github.com/diegoferigo/1c0a892e9f952be757e080e116e6cd6f
I tried to debug the function and the text is read-in but somehow the replacement does not work. No errors are produced by plot2latex

Florian

Hi Jan,
thank you for with extremely helpful package! I have a problem with the name of the y-axis: it is positioned too far on the left side because of the long label names X0001, X0002, ...
Is it possible to use shorter labels so the distance between the y-axis and the y-axis name is normal?
Thank you!

Hey Jan,
Thanks for this script! It really helps to create a LaTeX usable Plot directly from MatLab. But i ran into some issues using your script.
The first problem appears when i am saving with a legend. There are 10 entries in my legend and the first one is always missing. Additionally the legend box is too small so the text is sticking out of the right sight.
Is there already a solution for this problem?

Jan de Jong

Hey Heleen,

Thanks for your comments. Regarding your question, if you use 2015b or higher you can use the solution of Ben Blaser, and posted below on 8 August 2016. Let me know if it works.

Hi Jan,
I have exponents in my xaxis (*10^-4) and these are lost with Plot2Latex. Is there a solution for this?

Thanks in advance!

Very nice!

Thank you, Jan! Renderer and reducing the contour levels (thus size) fixed the problem. Keep up the good work!

Jan de Jong

Hey Dominik, Good to know that you like it. The problem arises that Matlab chooses its on renderer based on the size of the image. So what you could do is use the options to specify the renderer. See the help file how to do this. Be warned this will take a lot of time, therefore it is not set as the default.

options.Renderer = 'painters';
Plot2LaTeX(gcf, 'Test_painters',options)

Let me know if it works.

Good job! Works great for me exept for contours containing too much data. With R2017a this does not work for me:

Z = peaks(200);
contourf(Z,10)
Plot2LaTeX(gcf, 'Test')

It gives a bitmap-type .svg without recognizing the text anymore. However, Z = peaks(20) works fine! Do you have any idea how to fix this problem?

Peter Hurt

Works perfectly!
Had to change the Inkscape directory in the function but then it worked. Thanks!

Volker P.

For me it works perfect. Thank you!

Hello Jan de Jong,
yes that is correct. The polarplot function does not use cartesian axis. This is why matlab2tikz does not work too.
I got the script working without a legend by defining:

Labels = {}; right at the beginning of the script
and changing line 318 to if ~isempty(FoundLabelText) && ~isempty(Labels)

Well unfortunately i need the legend. But the result looks nice. Even with the polarplot axes.

PS: I use Matlab 2017a.

Jan de Jong

Hey Tobias, Sadly I was not able to reproduce your error as I work on an older matlab version. The polarplot function was introduced in 2016. I suspect they introduced a new axis type which requires some work to add. The older 'polar' works normally with the Plot2LaTeX function. Sorry that I will not able to help you in short notice.

Hello,
i have a problem using your skript. I tried to export a polar plot with and without a legend.
Unfortunately i get several errors.

with legend -> Expected one output from a curly brace or dot indexing expression, but there were 0 results.
Error in Plot2LaTeX (line 326)
'text-align:', Labels(iLabel).Alignment{1},...

without legend -> Undefined function or variable 'Labels'.

Error in Plot2LaTeX (line 321)
{Labels.LabelText},...

Any suggentions to solve this?

This is my minimal example to reproduce the error:

phi = linspace(0, 2*pi, 200);
polarplot(phi, sin(phi),'LineStyle', '-');
hold on
polarplot(phi, cos(phi),'LineStyle', '-.');
rlim([-1 1]);

%legend('bla' , 'blubb');
Plot2LaTeX(gcf , 'test');

Many Thanks!

Jan de Jong

Hey Laurenz,

Here is a solution which should work:

Include inside the for loop over all color bar object (before line 285) the following
% treat colorbar labels
iLabel = iLabel + 1;
Labels(iLabel).TrueText = ColObj(i).Label.String;
if isRightAx % if text is right aligned
Labels(iLabel).Alignment = PosAligmentSVG(1);
Labels(iLabel).Anchor = PosAnchSVG(1);
else % if text is left aligned
Labels(iLabel).Alignment = PosAligmentSVG(3);
Labels(iLabel).Anchor = PosAnchSVG(3);
end
Labels(iLabel).LabelText = LabelText(iLabel);
ColObj(i).Label.String = LabelText(iLabel);

And similarly in the restoration loop of the color bar (before Line 424)
iLabel = iLabel + 1;
ColObj(i).Label.String = Labels(iLabel).TrueText;

Hi Jan, I also have Mathias's colorbar label issue. Do you have a solution?

Jan de Jong

Thanks Murilo for the comments. Could you send me your figure via email? Than I will take a look to see what is going on.

Hello! I'm having some trouble using this function. No error shows up, but final output .pdf file has the temporary labels, e.g. X20, instead of the real labels. Is there some workaround for this?
Thanks in advance, and nice script.

MSleiman

Unlike in 'article' documentclass font is not well interpreted in 'IEEEtran.cls'...
Any thoughts why characters are not treated as Latex text in IEEEtran?

code for either options:
1- \documentclass[journal, onecolumn]{IEEEtran}
2- \documentclass[10pt]{article}

goldbattle

Nino

Works in general really well. thanks! Only thing I found: if you use "colorbar('eastoutside')", the alignment of the ticklabels is not correct in the svg output. any ideas? (R2016b)

Jan de Jong

Thanks Yukio Fukuzawa for the question. In my opinion the % sign (\% in latex) works quite well in Matlab -> Inkscape -> Latex. Can you send me an example in which it does not work?

Great work! Minor suggestion: the percent sign (%) needs to be escaped as well, otherwise it will result in invalid syntax for pdf_tex. (I know, this should be inkscape's job but currently it doesn't do it)

function strXML = EscapeXML(str)
% ESCAPEXML repaces special characters(<,>,',",&) -> (&lt;,&gt;,&apos;,&quot;,&amp;)
escChar = {'&','<','>','''','"','%'};
repChar = {'&amp;','&lt;','&gt;','&apos;','&quot;','\\%'};
strXML = regexprep(str,escChar,repChar);
end

Mathias

Hey Jan,

thank you for this great work! I have one problem using your code with this script:
surf(peaks);
cb=colorbar;
cb.Label.String='$A_\mathrm{b}$';
cb.Label.Interpreter='latex';
Plot2LaTeX(gcf, 'test');

Everything runs normal (so no error or warning) but the result is the following (only if there is a label at the colorbar): In the generated PDF from Inkscape the Text still reads X000 and so on (As far as I understand your workflow no text should be present in the Inkscape generated PDF file).

I have an idea why this problem occurs: I assume Matlab saves the plot (or at least the text) in case of a present colorbar-label in another way than it does normally. One further indicator for that is that Inkscape apparently does not recognize the text labels (this is the reason why they are still in the inkscape exportet PDF file). Your script does also not recognize them because they are still labelled Xxyz in the .svg-file before the file is processed by Inkscape. One further thing I have noticed: Usually the PDF contains several pages (maybe the layers/groupings from the SVG-File?) but with the colorbar label enabled this is not the case.

I also noticed that the colorbar label is not replaced by an Xxyz string.

Do you have any ideas how this can be fixed?

I am using Matlab R2016b at the moment.

Greetings
Mathias

Jan de Jong

Hey Daniel,

Currently I am not able to access and modify the legend properties in a correct way. The ugly workaround used for vertical legends is not working for horizontal ones. Maybe in future releases of Matlab these properties can be fully controlled and this can be added to the Plot2Latex function.
Greetings,
Jan

Jan de Jong

Hey Zac,

That is indeed interesting, can you send me a sample fig, than I can try to figure out what is going on.

Regars,
Jan

Zac Giles

Hi Jan,

I really like this package, its what I've been looking for for a while. I have found two places where it fails me though, and one failure lead to an interesting point on the other failure.
First thing I found was that the function crashes during the 'Restoring text in the .svg file', with the error:
Error in Plot2LaTeX (line 341)
StrCurrTemp = strrep(StrLine_old, ...
This is caused when I have titles spanning multiple lines within the plot, created by using sprintf and the newline character \n.
The second issue I have found is when trying to export uitables. plot2LaTeX doesn't try to turn the data in the tables into text (which is not a problem for me), but the problem I've found is that it doesn't fully populate the table with values. The interesting thing I found was when I have a multiline title, and it fails to run properly, the svg file that is left behind does have a fully populated table, but has the title X001, so somewhere between recreating the title, some of the svg is lost. I have tried exporting the table withought a header, but it seems as if plot2LaTeX still tries to create a header, and doesn't fully populate the table either. Sorry this comment has been so long, I didn't know how to explain it concisely. Let me know if you want some example files.

Zac Giles

Daniel S.

Hello Jan, thank you for the great script! I have the same problems as Magnus Dam (05 Sep). Do you have a solution for legend frames in horizontal orientation?
Thanks in advance!

jdruant

Thank you Jan, great script!

Felix H.

Hello Jan,

I'm trying to use your function to convert a polar plot made with the mmpolar function (see https://de.mathworks.com/matlabcentral/fileexchange/38855-comprehensive-polar-plots). The figure contains labels with \circ and \pm symbols, which leads to errors when Plot2LaTeX is executed:

Warning: Error updating Text.

String must have valid interpreter syntax:
0\circ

Warning: Error updating Text.

String must have valid interpreter syntax:
15\circ

...

The resulting .pdf can not be included in a latex document.

Could you please tell me a solution to fix this problem?

Regards

Jan de Jong

Hey Magnus, Can you send me these figs? Than I can try to fix it.

Magnus Dam

I two problems with this script.
1. When I change the legend orientation to horizontal the legend frame becomes too small and it does not seem to get fixed by using \vspace{} or \hspace{} in the legend entry.
2. When I set the legend position (so Location becomes 'none') the figure can not be exported with Plot2LaTeX due to some error.

The first problem is the most problematic for me. Do anyone have a solution?

The problem mentioned by me has been solved by Jan de Jong. Thank you!

Jan de Jong

Hey Florian, can you maybe send an example to me?

Jan de Jong

Hey Florian,

Thanks for the comment. This is indeed not implemented in the code. Currently there is no simple work around. I am sorry, and will fix this in future release

Great script!

I just have one remark on contour plots. The positioning of the numbers next to the colorbar of the contourplot is bad (x-axis and y-axis labels are perfectly positioned). The only way to solve it is to manually replace them in Inkscape. Any solutions for that?

Jan de Jong

Hey Peachy Quant, Thanks for your questions. I am still working the axis exponent bug. Ben Blaser suggested this work-around (version 2015b or higher), the following code can be used. In earlier versions this axis exponent is not accessible. So I will get back to you on this.

---- Ben Blasers work ----
I put it just above

%% process options, first set default
yCorrFactor = 0.8; % default
% do not set default renderer

-------------
% check for Axis Exponents
if h.CurrentAxes.XAxis.Exponent
text(h.CurrentAxes.XLim(2), h.CurrentAxes.XAxis.Label.Position(2),...
['x $10^{\:{' num2str(h.CurrentAxes.XAxis.Exponent) '}}$'], ...
'VerticalAlignment', 'top','HorizontalAlignment', 'right', ...
'Interpreter', 'latex')
end

if h.CurrentAxes.YAxis.Exponent
text(0, 1, ...
['\times $10^{\:{' num2str(h.CurrentAxes.YAxis.Exponent) '}}$'], ...
'Units', 'Normalized', ...
'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'left', ...
'Interpreter', 'latex')
end

PeachyQuant

I have had a problem in that in the graph produced, the y axis multiplier (i.e. x 10^-3 at the top of the y axis) is excluded. I then tried to prevent Matlab from using this format by using set(gca, 'YTickLabel', (num2str(round(get(gca,'YTick'),3)')) but this produced the error "Cell contents reference from a
non-cell array object.

Error in Plot2LaTeX (line 241)
Labels(iLabel).TrueText =
AxeObj(i).YTickLabel{j};"
when Plot2Latex was run. I then tried set(gca, 'YTickLabel', str2num(num2str(round(get(gca,'YTick'),3)'))) but this produced the same error.

Nevertheless, thanks for a great script!

Jakob

How do I use it under Linux typ OS? I get the error that the inkscape.exe has not been found.

I get error when I the run the code:

Warning: No .pdf or .pdf_tex file produced, please check your Inkscape installation and specify installation directory correctly.
> In Plot2LaTeX (line 371)

If I add the add line suggested by @Nickolas I get another error:

Undefined function 'export' for input arguments of type 'char'.

Error in Plot2LaTeX (line 361)
export LANG=en_US.UTF-8;export LD_LIBRARY_PATH="";export DYLD_LIBRARY_PATH="";[status,cmdout] = system(['"', DIR_INKSC, '"',...

I have mentioned my Inkscape installations directories correctly.
Can someone tell me why am I getting these errors?

Jan de Jong

Thank you for the comment and thanks for the work around. We have tested the code only on one type of Unix system. We will look into this further.

Nickolas

Nice work! I had to modify the function slightly for it to work on my system ( Debian 8 Linux, Matlab 2015b ). There was a problem with the system call on line 361 of Plot2LaTeX---I see errors like: "/usr/bin/inkscape: /opt/matlab/R2015b/sys/os/glnxa64/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /usr/bin/inkscape)"

I added the following string at the beginning of the command on line 361: 'export LANG=en_US.UTF-8; export LD_LIBRARY_PATH=""; export DYLD_LIBRARY_PATH=""; ', and now it works great. FYI, in case others have this problem. Thanks again!

Jan de Jong

@Andrew Boysen, thank you for comments. Can you send me an email with your settings and documents? The demo should contain one page.

I also had to add quotes, as John mentioned. For some reason, my pdf_tex file calls for 11 pages, but my pdf only has 10 (or using the demo, it calls for 28 pages, but the pdf has 27). I haven't figured out what I have wrong yet.

Jan de Jong

@John Kurelek, Good to know you like the script. I will look into your comments and update this for the new release. Can you contact me via my profile, I have some questions about your second comment

Thanks for a great script! A couple of comments:
1) I ran into an issue with spaces within the figure directory when making the cmd call to Inkscape. This was fixed easily by adding quotes around DIR_FIG + filanme + .svg/.pdf on lines 333-338
2) For some reason, less than signs (<) did make into the svg file. Not sure why.

Jan de Jong

@Alton, thanks for the feedback. To answer your question, I need more information. Can you contact me using my profile?

I'm having trouble editing the .svg file in Inkscape and then exporting to .pdf for inclusion in my Latex file. Any tips?

MSleiman

Great Work! Many Thanks...

Makes for a very quick workflow to get high-quality images in LaTeX. Now no longer need TikZ…

Great function for those who do not want the headaches of eps files combined with transparancy.
Replaces LaPrint for users of PDFTeX users.

Updates

1.2.0.0

- Made compatible for Unix systems
- Added a waitbar
- Corrected the help file
- Fixed file names with spaces in the name. (Not advised to use in latex though)
- Escape special characters in XML (<,>,',",&) -> (&lt;,&gt;,&apos;,&quot;,&amp;)

1.0.0.0

Changed logo

1.0.0.0

Added Logo

MATLAB Release Compatibility
Created with R2014b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: LaPrint, matlabfrag

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.


Learn About Live Editor