# Beautiful MATLAB figures in LaTeX

Probably the most important part of a (scientific) document are the figures. The main reason is that “a picture is worth a thousand words”. On this blog, quite a few post have been dedicated to figures (or floats in general) in LaTeX. Especially the post on how to use Inkscape to create figures with LaTeX fonts. I work a lot with MATLAB, a numerical computing environment, and the figures/plots it creates are pretty (compared to MS Excel for example). However, I can’t stand the fact that the fonts in my figures are not the same as in the rest of my document. Recently I discovered matlab2tikz, a MATLAB script that saves figures as TikZ scripts.
NOTE: If you don’t work with MATLAB, this post is probably not in your interest.

What you’ll be creating

## TikZ

TikZ is a TeX package for creating graphics programmatically. More info and examples can be found here. First of all, don’t let the word TikZ scare you! Personally, I never bothered to learn how TikZ work and I still don’t.

## MATLAB

Alright, let’s cut to the case. We’re going to create a standard figure in MATLAB and then export it to a TikZ code. Open MATLAB and open a new script in the editor. Next, type the following in order to plot a sphere:

sphere(30); title('a sphere: x^2+y^2+z^2'); xlabel('x'); ylabel('y'); zlabel('z'); axis equal

Save this script in a folder of your own choice.

Next, download the matlab2tikz files here. You’ll see a folder that contains two .m files: matlab2tikz.m and matlab2tikzInputParser.m. Copy these two files into the same folder as the sphere script you just created.

In order to generate the TikZ code, type the following in the MATLAB command window (assuming the plot of the sphere is still open):

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

The script now exports a .tikz file to your current folder. Find and copy this file into the folder where your .tex file is located.

## LaTeX

Now that the newly created .tikz file is in you LaTeX folder it time to do some TeXing. In the preamble of your LaTeX code, make sure the pgfplots package is called:

\usepackage{pgfplots}

The next thing is to implement the figure in your document. Add the following somewhere after the \begin{document} statement:

\begin{figure} \centering \newlength\figureheight \newlength\figurewidth \setlength\figureheight{6cm} \setlength\figurewidth{6cm} \input{mysphere.tikz} \caption{A plot of a sphere} \label{fig:sphere} \end{figure}

This code is pretty basic: a centered figure environment that calls mysphere.tikz and assigns a height and width of 6cm to that figure.

Compile your document and view the result! Beautiful isn’t it?

NOTE: Only insert the two command lines starting with \newlength... the FIRST time in your LaTeX document! Thereafter, LaTeX remembers the two commands and if you define them again it will result in an error.

## Editing the plot

If you’re not completely happy with the result, you can add small changes to the figure by editing the .tikz code. That is, if you have some knowledge on how to work with TikZ (I don’t). However, when opening the .tikz file we see a line of code saying:

view={-37.5}{30},

This is the same view command as used in MATLAB. Modifying this to:

view={0}{90},

gives us the xy-view of the sphere. Simple as that!

Furthermore, you probably agree with me that the title of the plot is not correct. The first part (‘a sphere:’) should not be in math mode. This can also be changed from within the TikZ code. Locate line 21 starting with the word ‘title’ and change this to:

title={a sphere: $x^2+y^2+z^2$},

Done!

More information about matlab2tikz can be found on the authors website, github page or on the matlab2tikz forum.

1. [...] have a problem with the horizontal alignment of an image. I have compiled the image from the matlab extension and added it to my LaTeX file with the following [...]

2. oaright says:

I integrated your example into my tex files, with the same matlab code and latex code. But when I generate DVI files with latex, it always show “broken pipe” when I open it with yap.exe?

So where I am wrong?

3. ihsan says:

thank you very much, just what i wanted

4. Stephanie says:

Hey! Thanks a lot for this tutorial. This was exactly what I was looking for!
But still it doesn’t work for my Matlab-Plot, I always get the error:

“package pgfplots Error: Illformed colormap specification. at line xx: …point meta max= 0.1]”

I get this error when tikz defines my colorbar and meta max is the maximum of the colorbar.
here is a part of the tikz-code:
colormap={mymap}{[1pt] rgb(0pt)=(1,1,1); rgb(16pt)=(1,1,0); rgb(40pt)=(1,0,0); rgb(63pt)=(0.0416667,0,0)},
colorbar, point meta min=-0.05, point meta max=0.1]

Any ideas what the error is about? Do I need some additional packages?
Thank you!

• Frits says:

Besides from xcolor I don’t think you need any additional packages. If you could post a minimal example, I might be able to help some more.

5. Stefan says:

wow, this is really great. it makes such a huge difference:)

just one thing doesnt work

when i manually add arrows to the plot in matlab they are not related to the plots anymore.
also textboxes dont appear at all anymore.
but since i think its quite important to have this to illustrate, i wanted to ask if somebody has a workaround.

thank you very much

• Frits says:

Hi Stefan,

You’re right, I think I’ll dedicate a separate post on making small adjustments to matlab2tikz figures.
In my experience, arrows and text indeed weren’t included in the TikZ figures. The ‘workaround’ I use is to add these manually. I know, it is a lot of work…

Anyway, to add text, put the following within the axis environment:
\node at (axis cs:12,20) {text here};
In this case, the text is printed at (x,y)=(12,20).

Adding arrows is similar, but a bit more code is needed. I’ll write a post on that as soon as I find some time.

• Julian says:

Hi Frits,

curiously I can add text to my figure only within the box of the plot, i.e. I cannot label special points at the x and y axes.

Do you know any solution to this problem?

• Frits says:

Hi Julian,

In order to add text outside the axis box, you’ll definately need to make changes in your .tikz file rather than in MATLAB itself. I don’t know a lot of TikZ commands by heart, because they are extremely well documented so I just look things up every time. So I suggest you do a search through the PGF/TikZ manual: Find it here.

• Julian says:

Hello Frits,

oddly, it does work now, even though I haven’t changed anything. :)

For anyone who wants to label points at the axes, consider

xtick={tick1,tick2,…}
to set ticks manually and to avoid interfering the ticks with your text labels.

Bye

• Frits says:

Plus, if you have a grid plotted the axis ticks will have grid lines aligned to them. If you don’t want this, use the extra ticks option:
extra x ticks={}, extra x tick labels={}

6. Victor says:

Hi Frits, I’m trying to create a figure consisting of three subfigures in a column. The code I use is this:

\begin{figure}
\centering
\begin{subfigure}
\centering
\setlength\figureheight{5cm}
\setlength\figurewidth{7cm}
\input{figa.tikz}
\caption{Subcaption a.}
\end{subfigure}%

\begin{subfigure}
\centering
\setlength\figureheight{5cm}
\setlength\figurewidth{7cm}
\input{figb.tikz}
\caption{Subcaption 2.}
\end{subfigure}%

\caption{General caption.}
\label{fgr:x}
\end{figure}

Unfortunately, miktex creates three different figures, 2 for the ‘subcaptions’ and 1 for the ‘caption’. Any idea how to solve this?

• Frits says:

Hi Victor,

The code you posted didn’t work for me, so I’m not sure if I understand your problem. However, I created a similar code (not using a TikZ figure but that should not matter) illustrating the use of the subfigure environment.
Visit https://www.writelatex.com/27282fpwtrq to view my answer on the writeLaTeX website.

7. Ruben says:

Hi,

Now, my questions:

I assume that the following line might be defined anywhere in the text, before the first figure, right?

 \newlength\figureheight \newlength\figurewidth \setlength\figureheight{6cm} \setlength\figurewidth{6cm} 

But what happens if I want to have figures with different sizes throughout the text. How can I do that?

Cheers!

• Frits says:

Hi Ruben,

Thanks for the compliment on my website!
Now, to answer your question: What I mostly do is defining the first two lines in the preamble. So add this before \begin{document}:
 \newlength\figureheight \newlength\figurewidth 

Then, right before I add a TikZ picture, I add the other two lines of code to define the size of that picture:
 \setlength\figureheight{6cm} \setlength\figurewidth{6cm} 

So, the setlength command redefines the figureheigth or figurewidth length. So if your second picture needs to be 10cm by 5cm, instead of the previously defined 6cm by 6cm, just add the following right before the second picture:

 \setlength\figureheight{10cm} \setlength\figurewidth{5cm} 

Hope this helps!

• Ruben says:

No I get it, so the problem is defining \figureheight \figurewidth more than once but not the actual height and width of every single figure.

Cristal clear!!

• David M says:

(“C:\…\mysphere
.tikz”

! Package pgfkeys Error: I do not know the key ‘/pgfplots/colormap/jet’ and I a
m going to ignore it. Perhaps you misspelled it.

I am using MikTex on Windows 7 and I also have included the following packages

\usepackage{pgfplots}
\usepackage{tikz}

Any ideas?

• Frits says:

Seems like the color scheme isn’t recognized. Did you load the xcolor package?

\usepackage{xcolor}

8. sandeep says:

i am unable to run matlab2tikz. i have old version of matlab
(R200b). can you help me how to run files in older version.

the following is the error

In matlab2tikz at 165
??? Error using ==> matlab2tikz at 318

what do you mean by the script.do you mean the .m file.??

• Frits says:

First of all, you write you have matlab version R200b. That must be a type, since the version should be in the form R200xb (R2008b, for example).
Anyway, I think you’re question is more matlab and matlab2tikz related and therefore I suggest you contact the creator of the matlab2tikz script. Find him here: https://github.com/nschloe/matlab2tikz

• sandeep says:

Hi…
i updated matlab version. now i am getting the pictures as u said in the tutorial. however x axis scale is showing automatically. how to set x-ticks to manual in .tikz file.

9. Maissa says:

Thanks for the nice tutorial :) so beautifullllllll good luck

10. Jeroen says:

I followed your step exactly but get an error “TeX capacity exceeded…”. Alternatively I used matlab2tikz to produce a .tex file but this also gave the same error. Any ideas what’s causing this?

• Jeroen says:

Just before the error this is logged:

(“D:\My Documents\…\myfile.tikz”
Missing character: There is no ; in font nullfont!

Runaway definition?

Could there be something wrong there?

• Frits says:

If you’re trying to compile a very, very large TikZ picture this error could be solved by expanding the memory allocated for the TeX engine. This is a rather difficult process and o get started, this might help: http://tex.stackexchange.com/questions/43430/how-to-increase-bufsize-for-lualatex-or-pdflatex
Alternatively, you could use the luaTeX engine (rather than pdflatex) to compile the document.

If the TikZ file is not large at all, the error might be due to some odd coding in the TikZ code. But my guess is that your code is just too long (I once experienced this when converting a matlab plot with a large number of datapoints).

11. says:

Thanks for posting! I have been trying to use it with Matlab’s plotyy to no avail. The axes get all messed up (y on top and other of the sort) any ideas?

12. Jonas C says:

Great post, this is exactly what I was looking for. I have run into a problem, however. When typesetting (which takes significantly longer now, but I guess that’s the price to pay) something throws up the error “undefined control sequence \end{axis}” in the .tikz file. Am I still missing a package? I had to install both pgf/tikz and pgfplots separately, could there be some kind of compatability issue?

• Frits says:

Hi Jonas,

That is probably due to an error that slipped in during the conversion from MATLAB figure to TikZ code. Unfortunately, the script matlab2tikz is not perfect.

Have a look at your .tikz file and check your axis environment: every \begin{axis} should be followed by an \end{axis}. Also, there might be a second \begin{axis} before the first \end{axis}.

PS: If find the compilation time taking too long now, there are some ways to speed things up. Search for ‘faster LaTeX’ on this site!

• jan says:

In my case I got this error due to a title that was too complex ().

• josombio says:

In my case I use the same plot in 2 different documents, and I get this problem only in one (funny). So, the output from Matlab2tikz seems to be OK, and I bet the problem is somewhere else. Removing the title does not help.

• Frits says:

If the actual code of the matlab2tikz figure is EXACTLY the same, my guess is that your problem lies in the preamble.

• julia says:

Hi!

I had the same mistake and I just changed these lines:
\newlength\figureheight
\newlength\figurewidth
in the tikz file AND in the latex file into:
\newlength\figureheightb
\newlength\figurewidthb

the next plot could be:
\newlength\figureheightc
\newlength\figurewidthc

• Frits says:

Although possible, that requires a lot more work than just defining 1 width and 1 length once:
\newlength\figureheight \newlength\figurewidth

And then, right before all tikz pictures:
\setlength\figureheight{...} \setlength\figurewidth{...}

13. Jan says:

Thanks for the nice tutorial. However, if I follow the tutorial using my figure I get the error

LateX Error: File ‘FILENAME.bb’ not found. Any ideas? I am compiling the code using latex.

14. Damien says:

Hi,

Thanks for the tutorial and for the MATLAB script. One question though :
Can I store my .tikz graphics in a subfolder of the main tex folder? I am used to keeping the graphics apart from the few main files (by adding \graphicspath{{./images/}} to the preamble).

Keep up the good work!

• Frits says:

Hi Damien,

Yes that’s possible. I always do that to keep the main tex folder as clean as possible.

For the example above, instead of

\input{mysphere.tikz}

\input{images/mysphere.tikz}
• Damien says:

Thanks!

15. Bootvis says:

Great post, thanks!

16. Thanks for this post. I agree completely: the only way to incorporate Matlab (or Octave) graphics in a Latex document and get truly good results, is via pgfplots and tikz.

You or your readers may be interested in a front-end to pgfplots that I wrote. I find it a lot easier to use than matlab2tikz, and a lot more flexible too. I use it all the time in my writing. The script is at

https://bitbucket.org/mbaz/octave-scripts/src/70e1dc976c6d/printpgf.m

The script includes some documentation and examples. I hope you find it useful!

17. Nico says:

If you know that you want to have the plot 6cm by 6cm, then you can of course go like

matlab2tikz(‘mysphere.tikz’, ‘height’, ’6cm’, ‘width’, ’6cm’);

and save a bit of LaTeX code.

• Frits says:

That’s true, Nico. However if you want to change the size of the figure afterwards you’ll need to open the .tikz file instead of just editing the .tex code.

But it’s indeed worth noticing, thanks for that!

• CA says:

Nico, are you the author of matlab2tikz? Thank you for the great work!