# Creating figures from matlab for use in latex (problem: activating legend changes figure size)

At the moment I am creating a lot of figures while writing my PhD thesis. As I am using a lot of Matlab I use the function matlabfrag to export my figure to LaTeX:

MATLAB

h = figure(1);
plot(rand(10),rand(10));
legend(random);
grid on

set(gcf,'defaulttextinterpreter','latex');

set(gca,'FontSize',font_axes);

ht = get(gca,'Title');
set(ht,'FontSize',font_title);

hx = get(gca,'XLabel');
set(hx,'FontSize',font_xy);

hy = get(gca,'YLabel');
set(hy,'FontSize',font_xy);

hl = findobj(gcf,'Type','axes','Tag','legend');
set(hl,'FontSize',font_legend);
set(hl,'Location','northeast');

xlabel(x_text,'FontSize',font_xy);
ylabel(y_text,'FontSize',font_xy);

set(gcf,'Units','inches')

set(gcf,'PaperPositionMode','auto')

set(h,'Position',[1 1 1+width 1+height]);

set(gca, 'Position', get(gca, 'OuterPosition') - ...
get(gca, 'TightInset') * [-1 0 1 0; 0 -1 0 1; 0 0 1 0; 0 0 0 1]);

matlabfrag(test);

saveas(h,figure_name,'fig')


LaTeX

\begin{figure}[ht]
\begin{minipage}{\textwidth}
\centering
\psfragfig[frame]{test}
\caption[short caption]{caption}
\label{fig:21}
\end{minipage} \end{figure}


This gives me a nice result. But now the problem is, while activating and deactivating the legend I obtain different figure sizes:

To be exactly, the figure size is the same, but the pictures seem to be cropped differently.

I know this is half a matlab problem. But I think a lot of people who use latex encouter this function in order to get nice latex plots for their thesis.

Hopefully someone can help me with this strange problem? As I plot a lot of figures on top of a new page these different heights of the figures are a big problem as the following text on a left and on a right handed page will not be on the same line.

Thanks in advance for your help! Also if someone knows an easier solution this would be really cool.

• I recommend the use of Matlab2tikz (mathworks.com/matlabcentral/fileexchange/…) instead. It involves a bit of work at the beginning but you have full control and you can compile with pdflatex. – pluton Aug 2 '16 at 22:32
• thanks a lot for your answer. As I already did a lot of work for matlabfrag I would really prefer using it. I am not quite sure anymore if my problem is still a 'more Latex' problem, so I asked for help in a matlab forum: gomatlab.de/viewtopic,p,167489.html#167489 – Mia Aug 3 '16 at 9:44