Skip to content

Instantly share code, notes, and snippets.

@alejandroastudillo
Created May 17, 2019 12:28
Show Gist options
  • Save alejandroastudillo/8c7e6b9cf3780c022f635bcc0a3f24c1 to your computer and use it in GitHub Desktop.
Save alejandroastudillo/8c7e6b9cf3780c022f635bcc0a3f24c1 to your computer and use it in GitHub Desktop.
LaTeX Tips

Figures with Matlab2Tikz

To install the Matlab2Tikz library, just follow the installation instructions in the Matlab2Tikz GitHub.

The easiest way to use the Matlab2Tikz library is with the custom function save_figure.

Just create an empty script, copy the following code, paste it in the script, and save it as save_figure.m. This script must be placed in the working directory of MATLAB, or you can include it into the MATLAB path.

function save_figure(fig_handle, fig_name, ppi)
%SAVE_FIGURE Saves any matlab figure in FIG, EPS, PNG or TIKZ format
%   The target resolution can be specificed as the number of Pixels Per Inch (PPI), e.g. 400 (default), 600,
    if nargin < 3
        ppi = 400; % set default resolution at 400 Pixels per Inch
    end
    % Save figure as FIG file
	savefig(fig_handle,strcat('fig_',fig_name,'.fig'));
    % Save figure as EPS file
        saveas(fig_handle,strcat('fig_',fig_name,'.eps'));    
    % Save figure as PNG file
        saveas(fig_handle,strcat('fig_',fig_name,'.png'));   
    % Save figure as tikz file
        cleanfigure('handle',fig_handle,'targetResolution', ppi);
        matlab2tikz('figurehandle', fig_handle, ...
                    'filename', strcat('fig_',fig_name,'.tex'), ...
                    'showInfo', false, ...
                    'showWarnings', false, ...
                    'width', '\figurewidth', ...
                    'standalone',false);
end

To use this function, you just need to assign a handle (for example my_fig) when you are creating a figure, and then call the function save_figure(my_fig,'custom_name',ppi) where 'custom_name' is the name you want to assign to the files created as: fig_custom_name.fig, fig_custom_name.eps, fig_custom_name.png, fig_custom_name.tex; and 'ppi' is the desired PixelsPerInch resolution. For example:

    my_fig = figure(1);
    plot(x,y);

    save_figure(my_fig,'custom_name',400);

Here is an example of how to use the generated Tikz figure (in fig_custom_name.tex) from LaTeX:

	\documentclass{article}
	
	\usepackage{tikz}
	\usepackage[utf8]{inputenc}
	\usepackage{pgfplots} 
	\usepackage{pgfgantt}
	\usepackage{pdflscape}
	\pgfplotsset{compat=newest} 
	\pgfplotsset{plot coordinates/math parser=false}
	\usetikzlibrary{plotmarks}
	\usetikzlibrary{arrows.meta}
	\usepgfplotslibrary{patchplots}

	%%% In case of a memory error, you should follow two steps:
            %%% FIRST: UNCOMMENT the two following options, and add .

	    % \usepgfplotslibrary{external} 
	    % \tikzexternalize


            %%% SECOND: you will need to enable 'shell escape' at the pdflatex compilation
                %%% In TexMaker you can just go to 'Options/Configure TexMaker', in the Commands tab you will have
                %%% a PdfLaTeX text entry, filled with something like:  pdflatex -synctex=1 -interaction=nonstopmode %.tex
                %%% add '-shell-escape' just after pdflatex, just like this: pdflatex -shell-escape -synctex=1 -interaction=nonstopmode %.tex

	%%% The idea of externalization is to compile each plot as a separate TeX job. This leads to a graphic which can be used in the main job. Thus each plot has its own memory requirement. This usually avoids needing to make TeX's memory bigger. At the same time, the resulting files can be kept between TeX runs, which will speed up compilation for the second and subsequent runs.


	\newlength\figurewidth
	\setlength\figurewidth{0.5\textwidth} % You can set the figure width as you want, even for each figure separately. Just take into account that, if you are using externalization, when you want to modify a figure property (e.g., width), you must first delete the generated pdf file from the figure you want to modify in order to see the changes.
	
	\begin{document}
		\begin{figure}
			\centering
			\setlength\figurewidth{0.9\textwidth}
			\input{fig_custom_name.tex}
			\caption{ My first matlab2tikz figure }
			\label{fig:myfirstfig}
		\end{figure}

		\begin{figure}
			\centering
			\setlength\figurewidth{0.5\textwidth}
			\input{fig_custom_name.tex}
			\caption{ My second matlab2tikz figure }
			\label{fig:mysecondfig}
		\end{figure}
	
	\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment