Code covered by the BSD License  

Highlights from
matlab2tikz

4.91837

4.9 | 56 ratings Rate this file 1062 Downloads (last 30 days) File Size: 66.3 KB File ID: #22022
image thumbnail

matlab2tikz

by Nico Schlömer

 

07 Nov 2008 (Updated 14 Apr 2013)

A script to convert MATLAB/Octave into TikZ figures for easy and consistent inclusion into LaTeX.

| Watch this File

File Information
Description

matlab2tikz supports the conversion of most MATLAB figures,
including 2D and 3D plots. For plots constructed with third-
party packages, your mileage may vary.

The workflow is as follows.

   1. Place the matlab2tikz script in a directory where MATLAB can find it.
      (the current directory, for example).
   2. Generate your plot in MATLAB.
   3. Invoke matlab2tikz by
              >> matlab2tikz( 'myfile.tikz' );

The resulting file can be included into any LaTeX document (by \input{myfile.tikz}). Don't forget to add

  \usepackage{tikz,pgfplots}

and optionally (as of Pgfplots 1.3)

  \pgfplotsset{compat=newest}
  \pgfplotsset{plot coordinates/math parser=false}

to the preamble of your LaTeX document.

To specify the dimension of the plot from within the LaTeX document, try

    >> matlab2tikz( 'myfile.tikz', 'height', '\figureheight', 'width', '\figurewidth' );

and in the LaTeX source

    \newlength\figureheight
    \newlength\figurewidth
    \setlength\figureheight{4cm}
    \setlength\figurewidth{6cm}
    \input{myfile.tikz}

If you would like to see more information, follow the development, submit a bug, or contribute in any other way, please visit matlab2tikz' web page at https://github.com/nschloe/matlab2tikz .

Acknowledgements

Matfig2 Pgf inspired this file.

MATLAB release MATLAB 8.0 (R2012b)
Tags for This File  
Everyone's Tags
embed, figure, latex
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (95)
18 May 2013 Axel Lødemel Holene  
16 May 2013 Miche  
12 May 2013 kevin

Error using matlab2tikz>patchcolor2xcolor (line 3523)
matlab2tikz:anycolor2rgbDon't know how to handle the color model 'interp'.

Error in matlab2tikz>getColor (line 3472)
[m2t, xcolor] = patchcolor2xcolor(m2t, color, handle);

Error in matlab2tikz>drawPatch (line 1982)
[m2t, xFaceColor] = getColor(m2t, handle, faceColor, 'patch');

Error in matlab2tikz>handleAllChildren (line 640)
[m2t, str] = drawPatch(m2t, child);

Error in matlab2tikz>drawAxes (line 829)
[m2t, childrenEnvs] = handleAllChildren(m2t, handle);

Error in matlab2tikz>saveToFile (line 487)
m2t = drawAxes(m2t, relevantAxesHandles(ix), alignmentOptions(ix));

Error in matlab2tikz (line 396)
saveToFile(m2t, fid, fileWasOpen);

12 May 2013 kevin

Error using matlab2tikz>handleAllChildren (line 674)
I don't know how to handle this object: light

Error in matlab2tikz>drawAxes (line 829)
[m2t, childrenEnvs] = handleAllChildren(m2t, handle);

Error in matlab2tikz>saveToFile (line 487)
m2t = drawAxes(m2t, relevantAxesHandles(ix), alignmentOptions(ix));

Error in matlab2tikz (line 396)
saveToFile(m2t, fid, fileWasOpen);

29 Apr 2013 Pedro

Nico, thanks for this submission, I'm sure many people benefit from it.
I have the same problem as Etienne, below: the ordering of Matlab patches in 3D plots is not correct, and has to be fixed manually, which may not be possible for large figures.

28 Apr 2013 kevin

Very useful. But how to keep the font name/color/size axis or title of figures?

26 Apr 2013 Arne

I would love to use this nice script but for some reason I cannot make it work. I am using Matlab R2009b under ubuntu with Kile. Even with basic code, it does not work.

I get the following error:
[PDFLaTeX] finished with exit code 1

./testpic.tex:1005 Missing \endcsname inserted};

./testpic.tex:Extra \endcsname};

Can anyone help?

16 Apr 2013 bersan.riccardo  
02 Apr 2013 Grzegorz Knor  
25 Mar 2013 Christoph

Matlab2Tikz is a great tool! Thanks a lot for sharing!
@ Nico: You did a fantastic work which helps me a lot. However, there is a minor thing you might want to change in a future release (currently unsing 0.3.2): If one is trying to convert a contour(f) plot and include the result in a tex file, one gets in trouble with the alignment. This is caused by the preamble of the resulting file, with some blank lines and the \definecolor command. In my latex distribution (miktex) every linebreak causes a small shift to the right (propably a 'blank' is interpreted) and as more colors are defined as further the figure is shifted. To avoid this behavior I added %% where the \defincolor is set up, and thus it reads: sprintf('\\definecolor{%s}{rgb}{%.15g,%.15g,%.15g}%%\n'
To get a really tight boundary box, some other lines in the preamble might need %-sign, too.
If you want me to, I can send you a simple example showing the problem.

Best regards,
Christoph.

24 Mar 2013 Otto Debals  
22 Mar 2013 Nico Schlömer

@Georg I could certainly make this an option. If you could file a bug at <https://github.com/nschloe/matlab2tikz/issues> and explain a little bit more about what format is needed, that'd be great.

20 Mar 2013 Georg

Works fantastic - I have just one little suggestion: Could you convert the RGB values of the plots to CMYK when defining the custom colors? This has proven to be necessary for correct color disply in the Adobe Reader when using pdflatex and seems to be a widely known problem

19 Mar 2013 Nico Schlömer

@Karthick You can use the resulting file with `latex` (generating a PS-document) as well as `pdflatex`, fonts come out just as they are in the LaTeX document, you can customize your plot after it's been generated, and probably a bunch of other reasons. All in all, when you compare MATLAB's generated PDF with the compiled output of matlab2tikz, you'll notice a distinct difference in quality.

19 Mar 2013 Karthick

its indeed a good package. But what advantage it has from "print as pdf" option in matlab?

18 Mar 2013 Etienne Coetzee

Dear Niko

I am trying to convert a 3d plot with many patches, but the ordering is incorrect. Some patches that should appear behind others, appear in front. I am not sure if this is a tikz problem, but was wondering if you have encountered this as well. Any help would be appreciated.

13 Mar 2013 Israel Vaughn  
04 Mar 2013 Nico Schlömer

@H VH Ayala: Try matlab2tikz('strict', true). That should put the ticks exactly where MATLAB has them.

24 Feb 2013 H VH Ayala

Hi,

How to set only pre-defined xticks on m2t?

Using the stem(.) command in MATLAB, one would only be interested to have only the values which there is data associated in the xticks.

regards

07 Feb 2013 Nico Schlömer

@Anke This is currently not possible with m2t alone, and I wouldn't even recommend it for line plots -- after all, m2t cannot tell which data is important for you and which can be stripped. I'd recommend for you to manually reduce the number of data points in your 3D plots until the TeX compilation time becomes bearable.

06 Feb 2013 Anke

Great tool, thanks! Only one question: how do I use the option 'minimumPointsDistance' correctly for surf plots? For normal plots, it works fine, but with surf, nothing happens...

06 Feb 2013 Afala

Works flawlessly! Good job!

17 Jan 2013 Caio  
09 Jan 2013 Martijn

perfect

08 Jan 2013 Sylvain Chev

A must-have for scientific publications. Thank you very much for your effort.

12 Dec 2012 Nico Schlömer

@Georg If you file a bug at https://github.com/nschloe/matlab2tikz/issues giving a few more details (like providing the PNGs that failed along with the MATLAB code), I can try to fix this.

12 Dec 2012 Georg

Works like a charm! Makes figures in latex look superb.

One little flaw though: When I overlay to axes, one containing an imge with transparency, the output is two PNGs which are all black.

05 Dec 2012 Afala

Just amazing!

05 Dec 2012 Afala  
04 Dec 2012 nnunes  
02 Dec 2012 Juan

This is the best piece of matlab/latex code I have ever seen!!.

20 Nov 2012 Nico Schlömer

@H VH Ayala:
Do those styles allow for \usepackage{pgfplots}? That would be the only condition.
Also, by using Pgfplots' 'externalize' feature, you can convert those plots into PDFs which should be natively supported by any journal. (You may want to check out the 'standalone' option for matlab2tikz as well.)

19 Nov 2012 H VH Ayala

Is the TikZ file included in the tex file generated by the script compliant to journal submissions like Elsevier and IEEE?

16 Nov 2012 Alessandro Magnani  
06 Nov 2012 gbernardi

Armin Schoisswohl's solution did the trick! ;)

06 Nov 2012 gbernardi  
25 Oct 2012 Frederik Schrader

Dear Nico,

is there a way to manipulate the order of the plot elements? It doesn't seem respect it as soon as I plot data points and lines, e.g. plot(x,data,'k.',x,fit,'r-') plots the black points in the foreground, regardless of Matlab's plot order, rendering the red line practically invisible for large datasets. The same problem occurs with 'ko', while 'k-', i.e. lines for both elements, works like charm and places them in the correct order.

Thanks in advance

18 Oct 2012 Armin Schoisswohl

@gbernardi:
\text is defined in the amsmath package. Try to include '\usepackage{amsmath}' in the preamble, this should solve your problems.

18 Oct 2012 H VH Ayala

@gbernardi
Did you try the following?

plot(x,y)
legend({'your text here'},'Interpreter','latex')

17 Oct 2012 Nico Schlömer

@gbernardi
matlab2tikz tries to be smart about how tags and labels look like, but may fail sometimes. Try setting 'parseStrings' to false.
If that doesn't help, a bug report with a small example code on https://github.com/nschloe/matlab2tikz/issues would be appreciated.

17 Oct 2012 gbernardi

Great tool, but I'm experiencing problems with the legends.
What I write in the legend command in matlab is enclosed in a $\text{}$ environment and the \text{} part gives an error when compiling... Do you know why?

19 Sep 2012 leo nidas

Seriously I just saw my previous rating to your file in 2010 and I assure you that that was done by accident! I usually do not rate files, let alone give one star with no reason!This is a great tool so I hope my current rating somehow correct things. Is there a way to delete my previous rating or something?Thanx for sharing!

14 Sep 2012 Muhammad Asif ARAIN

Guys, I am not able to convert an errorbar with uneven min and max values. It says that currently this code can convert only even min and max values. Any one found a solution? Thanks in advance.
Asif

13 Sep 2012 Miche  
15 Aug 2012 Chris

Excellent script, makes professional looking plots with ease. Thanks!

15 Aug 2012 Chris  
14 Aug 2012 John Boissard

Hi,
I had the same problem as Nicholaus Halecky. You can insert \pgfplotsset{scaled ticks=base 10:0} at the preamble of your document and it should do the trick (at least if you are using datetick).

Cheers

14 Aug 2012 John Boissard  
06 Aug 2012 Alp  
15 Jun 2012 Carlos  
24 May 2012 JoseMauricio  
30 Apr 2012 Ricardo Santiago Mozos

A great tool.

23 Apr 2012 Tor Inge  
10 Apr 2012 Andreas

Hi everybody,

I figured out another problem:

Somehow, matlab2tikz is not able to process >>plot3(xvector,yvector,zvector)<< files.

Even the most simple example does not work:

% ###################################################################

x = rand(100,1)*4-2;
y = rand(100,1)*4-2;
z = x.*exp(-x.^2-y.^2);

% Construct the interpolant
% F = TriScatteredInterp(x,y,z,'nearest');
% F = TriScatteredInterp(x,y,z,'natural');
F = TriScatteredInterp(x,y,z,'linear');

% Evaluate the interpolant at the locations (qx, qy), qz
% is the corresponding value at these locations.
ti = -2:.25:2;
[qx,qy] = meshgrid(ti,ti);
qz = F(qx,qy);

hold on
surf(qx,qy,qz)
plot3(x,y,z,'o')
view(gca,[-69 14]);
hold off

matlab2tikz( 'testplot3D.tikz', 'height', '\plothoehe', 'width', '\plotbreite', 'parseStrings', false);

% ###################################################################

14 Mar 2012 Truong  
24 Feb 2012 Rhymer Yang

Compare with matlabfrag, I like matlab2tikz better. The quality of tikz output is superb! Great work! Thanks!

18 Feb 2012 Nico Schlömer

It does exist and is called 'minimumPointsDistance'.

18 Feb 2012 K Prakasam

matfig2pgf code has an option to reduce the number of data points. Can u include same algorithm in ur code also!...

17 Feb 2012 Nico Schlömer

Yeah I'd need the MATLAB code (e.g. by mail). That said, the warning seems to be clear: "Color bar sizes will likely need tweaking." It probably says that for a reason. ;)

17 Feb 2012 3d plots

i have the open plot and input:

matlab2tikz( 'myfile.tikz', 'height', '10cm', 'width', '5mm' );

...works fine with 2D-plots.

...or is it the plot-code you're asking for?

17 Feb 2012 Nico Schlömer

Example code?

16 Feb 2012 3d plots

hi.

thanks. very useful script...generally. but i have a problem with my 3d-plots when the colorbar is displayed...i get the error message:

"Warning: Physical units of x- and y-axis do not coincide (x: mm; y: cm).Color bar sizes will
likely need tweaking."

"Error in ==> matlab2tikz>getAxisTicks at 3852
s = str2double( tickLabel{k} );"

is there any solution to this? thanks in advance.

25 Jan 2012 Dimitris K

Great work! Thanks

16 Jan 2012 Nico Schlömer

Tim: Easy. Just use

>> matlab2tikz( 'myfile.tikz', 'height', '\figureheight', 'width', '\figurewidth' );

for all of your figures and set \figureheight and \figurewidth once in your LaTeX document.
See the README.

16 Jan 2012 Tim Sønderby

Can you make so that the size of the figure always is the same, that would make it easier to control it for consistency in a report.

Thanks - great work!

27 Dec 2011 Nico Schlömer

There's always interest in patches to matlab2tikz! You could send a pull request on GitHub, or send the patch through by mail (use git format-patch to get properly credited) or create a pull request on GitHub. I don't mind either way.

27 Dec 2011 Eike

Three things:
1.: Awesome piece of code. Really saves a lot of time and work.
2.: I set the width an the hight via "\pgfplotset{}" in my preamble and just change it for a few plots. Matlab2tikz always outputs width and heigh parameters which in this case isn't very usefull.
(just found the Wiki which provides a good work around for that https://github.com/nschloe/matlab2tikz/wiki - "\newlength and \setlength")
3.: I added support vor the "Legend.Orientation" parameter as well as for "Loaction=SouthOutside" and "Location=NorthOutside", are you interested in the code? Where to should I send it?

29 Nov 2011 Nico Schlömer

Hi Sebastien,

the #-issue should be fixed now; thanks for the report.
At the moment, I don't think pgfplots has a way of controlling the legend box aspect ratio in any way, but you may want to skim through its manual. Let me know in case you find something!

29 Nov 2011 Sebastien PARIS

Sounds great in a first try.

One thing, if my xlabel is xlabel('# K') in matlab, the produced file is buggy (manually changed xlabel={# K} to xlabel={\# K}) in the tikz file).

How to keep the aspect ratio for legend ?

14 Nov 2011 Francesco Montorsi

very nice script!! I've been using MATLAB EPS export and then editing with Inkscape and saving as PDF+LaTex solution so far, but this one is simpler and better as it solves in an elegant way the label positioning problems of my former solution!
Thanks!

03 Oct 2011 THB  
08 Sep 2011 Igor

Hi Nico,
Thanks again for the great work.

Few requests:
1. Is it possible to have a command line switch to put all Matlab legend entries just in {}, instead of $$ + \text{}? My legends are mostly non-formula, so I can format them much easier if they come through matlab2tikz in this shape.

2. I propose to put "defining custom colors" section before \begin{tikzpicture} because if you make legends in the fig. caption (by using \label{} and \ref{}), LaTeX will report an error without this, since \definecolor is only scoped to tikzpicture.

3. Related to 2: Any chance of automatic labeling of plots? For example \label{filename-p1}, \label{filename-p2},....

Thanks,
Igor

02 Sep 2011 Michael Melzer

Hi Nico,
it might be better to use filename an path of uiputfile (line 206, 212, 218, ...), so files can be stored elsewhere than the current folder.

Thank you.

02 Sep 2011 Michael Melzer  
17 Jun 2011 Mukhtar Ullah

I have emailed you my modification to the nested function drawText in order to deal with problems in text objects created using Matlab TEXT command. If you agree with that, you could update your code accordingly and save me from modifying everytime there is a new version. Thanks.
Mukhtar

07 Jun 2011 Nico Schlömer

@Alexander Klein: I implemented one or two things, you may wanna check out the latest release.
For future changes, it's best to submit a bug report at https://github.com/nschloe/matlab2tikz/.

19 May 2011 Nico Schlömer

Well, the documentation may not be up-to-date all the time.
In general it's always worthwhile to take a peek at https://github.com/nicki/matlab2tikz/.
All the options are also listed in the source file itself of course, so you can always look at lines 125 ff. Should be pretty self-explainatory.

1) Not sure I understand what you mean.
2) You mean the image width? There are 'width' and 'height' arguments.
3) Option 'mathmode'.

Generally, if you found a bug or similar, it's easier for me to follow it up on GitHub.

19 May 2011 Nicholaus Halecky

Thank you, Nico, the script is a work of art. I am an experienced LaTeX user (what I used to write my dissertation), and very comfortable in MatLab (minus any major plot generation). Thus, when I found your code, you can imagine how thrilled I was as I am building scripts for report generation at this time. This would be, easily, the best script I have ever encountered on this file exchange if I could find how to:
1) Remove the 10^5 in the x-axis label (I also use datetick and have added the suggestion by Mukhtar to the LaTeX preamble to no avail).
2) Predefine line width, image aspect ratio, and some sort of a scaling parameter, so that the output width and height parameters in the tikz, e.g.,

width=0.90\textwidth,
height=0.35\textheight

3) Some sort of understanding of how I can specify whether or not the title, axis labels, legends not be interpreted in LaTeX math mode (or do you suggest that I hard code this)?

Perhaps such features are supported (as mentioned by Petter), however a quick browse through the m file didn't give me much of a starting point.

@Alexander Klein, I am interested to know if your improvements were ever implemented by the author?

Thanks all for everything,
Cheers!

02 Feb 2011 Matt Bauman  
02 Jan 2011 Petter

It was because matlab2tikz wrapped my x and ylabels with $..$. I removed that piece of code and got my expected results.

29 Dec 2010 dm

@Petter: You have an example-code for which the spaces in xlabel doesn't work? In all my figures it works perfectly, so I assume it's something with your code.

Otherwise you don't use \includegraphics with TikZ figures (unless you pre-compile to PDF or something), but using the width/height commands already available will set the dimensions of the figure (these commands are also documented in the description here on FEX).

D.

28 Dec 2010 Petter

Spaces in xlabel doesn't seem to work

27 Dec 2010 Petter

Seems it was already supported, but not documented.

27 Dec 2010 Petter

Looks good, but I am missing the functionality to keep the aspect ratio and change the width. E.g., \includegraphics[width=3cm]{image}

The help does not cover the optional arguments.

22 Dec 2010 Alexander Klein

Hi everybody!

first of all: Thank you Mr. Schlömer for matlab2tikz. This is a great piece of a software.

Unfortunately, I have had the following problems when using version 0.0.7 in Matlab 2009b on a 64bit Linux system:
1. Labels and titles could not be written by sprintf, since it where cells.
2. Barplots did not work, since there was a typo (e.g. m2t was missing)
3. I need to plot time signals with a very small difference. That is why the precision in the pgfplots coordinates were not sufficient.
4. When plotting data series with several thousand data points, it took minutes to write the file (due to strcat and a lopp for i=1:length(xData)

I have made changes to the file which takes care of this issues:
1. e.g:

if iscell(title)
title = title{:};
end

2. for me replacing
barplotTotalNumber = barplotTotalNumber + 1;
with
m2t.barplotTotalNumber = m2t.barplotTotalNumber + 1;
helped
3. I added an option for the script where you can add a precision of the format string that is used when writing to the pgf file
4. I replaced the for loop with a repmat construction that reduced computation time a lot.

If anybody has encounters the same issues, I can send this file to Mr. Schlömer maybe (if he likes to add the changes). Or is there a better way to take care of that?

Kind regards

Alexander

14 Dec 2010 dm  
29 Nov 2010 Igor

Works great!
Thanks!

07 Oct 2010 Mukhtar Ullah

Wondeful tool. Today, I tried it and it could be no better than that. I faced that same problem ( that annoying x10^5), as mentioned by Paul, but that has nothing to do with malab2tikz.m but the way pgfplot processes the tick labels. I found a solution, though, which I would like to share and request Nico to include it in the readme file.
Add this to your latex document preamble
\pgfplotsset{x tick label style={/pgf/number format/fixed}}
\pgfplotsset{y tick label style={/pgf/number format/fixed}}
Of course, you do not need that if you are happy with the x10^5 notation.

20 Sep 2010 Ngo Huy

Hi everybody ! My name Ngo Huy . i am studient four year of Ho Chi Minh University of industry . I have a project graduated processor image (Product Classification in (closed chain stoppers)
help me . i use PLC s7200 , matlab 7.1

23 Jul 2010 Paul

Hi,

Amazing tool !!! Thank you very much.

I have an annoying problem though. I have coordinates imported from as matlab serial dates, which I then re-label using xtick. Works fine except when pgf plots the graph there is an annoying x10^5 in the bottom right corner (which must originate from the matlab serial date values.)

i.e., the code I have is :

\begin{tikzpicture}

\begin{axis}[%
view={0}{90},
scale only axis,
width=\figurewidth,
height=\figureheight,
xmin=724642, xmax=733408,
ymin=0, ymax=3.5,
xtick={724642,725373,726103,726834,727564,728295,729025,729756,730486,731217,731947,732678,733408},
xticklabels={84,86,88,90,92,94,96,98,00,02,04,06,08},

Could somebody please help me with this?

Best regards
Paul

02 Jun 2010 dm  
09 Apr 2010 Craig

Excellent Tool, plots come out looking great!

29 Jan 2010 Jean-Baptiste Carré

A really useful package. I hope it will support every plot types soon (particularly the scatter type ;-))!

10 Mar 2009 David Haberthür

I've used this submission extensively to add plots to my LaTeX-Files and it works like intended. Thanks for that submission!

10 Nov 2008 Jody Klymak

This would be much better if you explained that one needs to upload pgf and pgfplots latex packages and call \usepackage{pgfplots} in the preamble of your LaTeX document. After that it seems to work alright.

Updates
14 Mar 2013

update to 0.3.0

14 Mar 2013

upgrade to 0.3.2 (for real this time)

14 Apr 2013

update to 0.3.3

Contact us