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

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

69 Comments

  1. Hi friends, how is all, and what you wish
    for to say concerning this article, in my view its truly amazing designed for me.

  2. Ren says:

    Thank you for the tutorial.

    Can you please tell me how to add a data cursor tip to the plot? The data cursor I added to my plot does not appear in Latex and I’m getting a warning: Don’t know class ‘matlab.graphics.shape.internal.PointDataTip’. Default handling.

    Thank you.

  3. Phila says:

    Hi,

    Thanks so much for this practical way to add matlab figures. I was wondering how I can change the size of a textbox I add on a matlab figure when using the command matlab2tikz ?

  4. Roger Gomez Nieto says:

    Gracias, un articulo muy util.

  5. […] found this neat post with a link to a script to create TikZ drawing code from MATLAB plotting tools, however […]

  6. Aimée says:

    I downloaded what I thought were the relevant packages, but every time I compile it keeps asking for something else… Now I’m at a mkii file which it doesn’t even give me the option to save as a file type. :( Whhhhhhy is it never simple, when it is meant to be?

  7. Danny says:

    Thank you,

    This was enormously helpful! x

  8. I don’t even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you are going to a famous blogger if you are not already ;
    ) Cheers!

  9. […] came to my attention in the past month and have been using the simple tutorial from HowToTeX. It has worked great so far only one issue remains, I am unable to anchor the ylabel to the […]

  10. Asad says:

    Thanks a lot for the post..

    updater.m must be kept in same folder. otherwise it didn’t work properly.

  11. JJMD says:

    I’m getting errors when specifying my own mxnx3 color matrix CData, such as when using surf(X,Y,Z,CData). The error I get is: “! Package pgfkeys Error: Choice ‘color input’ unknown in key ‘/pgfplots/mesh’. I am going to ignore this key”. I can’t seem to find the problem, probably because I’m not experienced with tikz files.

    • JJMD says:

      Found it. Apparently I had an older version of pgfplots installed. It has to be version 1.8 or higher to support user defined color data. I found out that my version was outdated when even the backward configuration command ‘\pgfplotsset{compat=1.8}’ did not work. An outdated version may in fact be the evildoer of a lot of the problems posted here.

      The safest way to update your packages is to update them via your TEX distributor. If using MikTeX, go to (Windows) All Programs > MikTeX > Update (in admin mode) and click next… or use cmd and type mpm –find-updates to see for which packages updates are available and then type mpm –update=[package] to update the specific package. NOTE: you may not be allowed to update a package prior to updating a number of ‘main’ packages. This likely occurs when you have not updated your TEX distributor for a long time. In this case, the MikTeX updater will select only these packages. Don’t manually check other ones and just update the selected ones first. Then run the updater again and you will see that all the other packages are selected to be updated. After having successfully updated all the packages, mpm –find-updates in cmd should return ‘There are currently no updates available.’

      • Allan says:

        Having the exact same issue, except i still get the error no matter if i use version 1.8 or the newest 2.10 of pgfplots.

  12. Nguyen says:

    hello, i wanna edit a matlab figure before integrating this figure in latex document. can you show how to do that? does it work by using inkscape or any software else? thank you!

    • Frits says:

      One way would be to use matlab2tikz as shown in this post. Another option would be saving the MATLAB figure as .eps and edit that file in Inkscape (see here).

  13. Anne says:

    I’m also using matlab2tikz and I get problems using this tool for root locus plots. Even after setting axis limits scaling of the x-axis is [-5*10^95, 2*10^98]. y-axes causes no problems. For other plots everything works fine.
    My code:
    h=rlocusplot(G_IO);
    p=getoptions(h);
    p.Grid=’on’;
    p.Title.String = ‘WOK innen’;
    p.XLimMode=’manual’;
    p.YLim=[-45 60];
    p.XLim=[-40 1];
    setoptions(h,p);
    matlab2tikz( ‘test.tikz’ );

    Thanks for help!

    • Frits says:

      I haven’t got any experience with the matlab2tikz setup for root locus plots. So I’m not sure whether the problem is on the ‘MATLAB side’ or the ‘TikZ side’. What error shows up when you compile your .tex file?

      • Anne says:

        I do not get an error. The tikz file throws a warning:

        “Axis range for axis x is approximately empty; enlarging it (it is [0.0:0.0]) on input line 265.”

        Before I fixed the axes manually I had this problem/warning for both axis.

  14. Javing Fun says:

    I’ve done everything you’ve mentioned.
    I have this in my preamble:

    \documentclass{article}
    \usepackage{pgfplots}
    \usepackage{tikz}
    \usepackage{xcolor}
    \pgfplotsset{compat=1.8}

    my error is as follows:

    ! Undefined control sequence.
    \text

    l.1006 \end{axis}

    What am I doing Wrong?

    • Frits says:

      The problem is \text command in your .tikz file. Matlab2tikz has the habit to make normal text that is next to math text very complicated. Something like

      Two is $2$

      Would be written as

      $\text{Two is }2$

      by matlab2tikz (note that this is just a silly example.

      Anyways, for the \text command you need the amsmath package in your preamble.
      So \usepackage{amsmath} should solve your problem.

  15. Dave Epic says:

    Hi this package is excellent, thank you for a well written article.

    I have spent a little time playing with the sphere example. I have one question, is there a way to keep the box on the plot. For example in Matlab I run the following:

    x=rand(10,1);y=rand(10,1);z=rand(10,1)
    figure
    scatter3(x,y,z,’filled’)
    xlabel(‘x’); ylabel(‘y’); zlabel(‘z’);
    axis equal; box on; grid on;

    I then export to a TixZ file.

    When the file is added to LaTex I lose the ‘box on’ formatting, which ideally I’d like to keep. If anyone has any ideas I’d be really grateful! Cheers.

    • Frits says:

      Hi Dave,

      That’s a conversion error caused by matlab2tikz. Although I’m not able to test this right now, I’m pretty sure you can fix it by adding the following line to the axis environment in the TikZ file:

      axis lines*=box

      For 2D plots, matlab2tikz adds axis lines*=left to the code. Overwrite that one if it’s present.

      Hope this helps!

  16. marryj says:

    Hello,

    first of all: Very Good Tutorial! Thanks for it.

    I have a problem with the tikz-file and i don’t know how to fix it.

    The label of my y-axis overlapes with the scale on the y-axis. The reason is that the values ​​of the scale are very small and are multiplied by 10^-3. Instead of 10^-3 is on the top (as in the x-axis), all values of the scale are multiplied with it seperately, e.g.
    1 * 10^-3
    8 * 10^-4
    6 * 10^-4

    and so the label overlapes with the first column of values. I don’t understand why is in the right form in the x-axis but not in the y-axis. In my Matlab-figure there is everything ok.

    I hope i explained it understandably and somebody has a solution for this problem.

  17. […] 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 […]

  18. 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?

  19. ihsan says:

    thank you very much, just what i wanted

  20. 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!

  21. 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={}

  22. 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.

  23. Ruben says:

    Hi,

    First of all, I wanted to congratulate you about this site. The tips are excellent!!! :-)

    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:

        Thank you for your quick reply :-)

        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!!

      • Torbjorn says:

        You really should have written this in the post as well. Actually, I would recommend having both \newlength and \setlength commands in the preamble, and if you need to change the size of a figure, add a new pair of \setlengths inside the figure in question.

        I have seen the note below that code snippet, but I really think it is bad idea to define the lengths inside the figure in the first place. I would consider editing the blog post.

        (And if this has been commented on previously I apologize, in my laziness I haven’t read all of the comments, and I am aware this post is three years old.)

    • David M says:

      Hello, I read this article and tried to implement it, getting this error:

      (“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?

  24. 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
    MATLAB figure not found.

    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.

  25. Maissa says:

    Thanks for the nice tutorial :) so beautifullllllll good luck

  26. 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).

  27. 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?
    Thanks in advance!

  28. 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 ($$).

        • João André says:

          I second this.

          Was getting this error because of the title. Replaced with a simple “Figure” string and it compiles ok.

      • 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{...}

  29. 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.

  30. 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).

    Thanks in advance,

    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}

      you’ll need to add

      \input{images/mysphere.tikz}
  31. Bootvis says:

    Great post, thanks!

  32. 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!

  33. 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!

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>